【问题标题】:Running Time (Empty for loop vs for loop with one statement)运行时间(空 for 循环 vs for 循环与一条语句)
【发布时间】: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


【解决方案1】:
  1. 在启用优化的情况下构建您的应用。
  2. 使用比 GetTickCount 更好的计时方法,例如查询性能计数器
  3. 通过经常测量经过的时间并丢弃异常大的样本来检测上下文切换。

如果您执行上述操作,则两个循环应该花费相同的时间,因为 x 未使用,编译器可能会完全丢弃该语句。如果循环也被完全丢弃,也不会感到惊讶。

在测量性能时,对真实代码使用分析器。

【讨论】:

  • +1 - 是的,如果 x 没有在任何地方使用,我不会惊讶地看到编译器优化了两个循环。
【解决方案2】:

我怀疑问题出在您的时间来源上。以下 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多