2011-03-07 119 views
1

我有以下程序,我在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; 
} 
+0

在調試模式下的時序非常不可靠。你可以瞭解性能的重要性,但要想獲得比這更好的結果是相當困難的。 – 2011-03-07 02:32:36

回答

2
  1. 構建應用程序與優化開啓。
  2. 使用比GetTickCount更好的計時方法,例如, QueryPerformanceCounter
  3. 通過經常測量經過時間來檢測上下文切換,並丟棄異常大的採樣。

如果你這樣做,兩個循環應該花費相同的時間,因爲x未被使用,編譯器可能會完全丟棄該語句。如果循環全部被丟棄,也不會感到驚訝。

測量性能時,在實際代碼上使用分析器。

+0

+1 - 是的,如果在任何地方都沒有使用x,編譯器會優化兩個循環,我不會感到驚訝。 – 2011-03-07 02:31:37

0

我懷疑問題是你的時間源。下面的VB代碼從不執行簡單的加法循環比空循環更快。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Const loops As Integer = 100000000 
    ListBox1.Items.Clear() 

    Dim precTM As Long = Stopwatch.GetTimestamp 
    For x As Integer = 1 To loops 
     'nothing 
    Next 
    precTM = Stopwatch.GetTimestamp - precTM 

    ListBox1.Items.Add(precTM/Stopwatch.Frequency) 
    ListBox1.Refresh() 

    Dim foo As Integer 
    precTM = Stopwatch.GetTimestamp 
    For x As Integer = 1 To loops 
     foo = x + 1 
    Next 

    precTM = Stopwatch.GetTimestamp - precTM 
    ListBox1.Items.Add(precTM/Stopwatch.Frequency) 


End Sub