我有以下程序,我在 VS 2010 Debug模式下运行它。令我惊讶的是,空的 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;
}
最佳答案
- 在启用优化的情况下构建您的应用。
- 使用比 GetTickCount 更好的计时方法,例如查询性能计数器
- 通过经常测量耗时并丢弃异常大的样本来检测上下文切换。
如果执行上述操作,这两个循环应该花费相同的时间,因为 x 未被使用,编译器可能会完全丢弃该语句。如果循环也被完全丢弃,也不会感到惊讶。
在测量性能时,对真实代码使用分析器。
关于algorithm - 运行时间(空 for 循环与一条语句的 for 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5214850/