【发布时间】:2011-07-10 01:09:03
【问题描述】:
我有以下程序,我在 VS 2010 调试模式下运行它。令我惊讶的是,空的 for 循环比带有加法语句的 for 循环花费的时间更多。空for循环的时间为2371 ms,添加for循环的时间为2043 ms。我跑了好几次,每次空的 for 循环都更快。怎么回事?
#include <Windows.h>
#include <iostream>
using namespace std;
int main(){
DWORD start = GetTickCount();
for(int i = 0; i < 1000000000; i++){
}
DWORD finish = GetTickCount();
cout<<finish - start<<" ms."<<endl;
start = GetTickCount();
for(int i = 0; i < 1000000000; i++){
int x = i + 1;
}
finish = GetTickCount();
cout<<finish - start<<" ms."<<endl;
return 0;
}
【问题讨论】:
-
调试模式下的计时非常不可靠。您可以了解性能的大小,但很难获得比这更好的效果。
标签: algorithm loops time for-loop performance