我有以下程序,我在VS 2010 Debug模式下運行它。令我驚訝的是,for循環比for語句花費更多的時間。空循環的時間爲2371毫秒,爲循環添加的時間爲2043毫秒。而且我多次運行它,每次空循環更快。到底是怎麼回事 ?運行時間(空for循環vs 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;
}
在調試模式下的時序非常不可靠。你可以瞭解性能的重要性,但要想獲得比這更好的結果是相當困難的。 – 2011-03-07 02:32:36