运行时间(空循环VS for循环用一条语句) [英] Running Time (Empty for loop vs for loop with one statement)

查看:738
本文介绍了运行时间(空循环VS for循环用一条语句)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的程序,我对VS 2010的调试模式下运行它。令我吃惊的是空循环正在采取更多的时间比for循环与另外声明。时间的空循环是2371毫秒和另外的循环时间为2043毫秒。我跑了几次,每一次空循环比较快。这是怎么回事?

 的#include< WINDOWS.H>
#包括<的iostream>

使用名字空间std;

诠释的main(){
    DWORD开始=的GetTickCount();
    的for(int i = 0; I< 10亿;我++){

    }
    DWORD完成=的GetTickCount();
    COUT<<完成 - 开始 -  LT;<MS<< ENDL;


    开始= GetTickCount的();
    的for(int i = 0; I< 10亿;我++){
        INT X = 1 + 1;
    }
    完成=的GetTickCount();
    COUT<<完成 - 开始 -  LT;<MS<< ENDL;
    返回0;
}
 

解决方案
  1. 在构建应用程序与优化打开。
  2. 使用一个更好的计时方法比GetTickCount的,如QueryPerformanceCounter的
  3. 通过测量经过时间的时候,并丢弃异常大的样本检测上下文切换。

如果你做到以上,两个循环应采取的时间是相同的,因为x是未使用编译器将可能只是丢弃的发言完全是。会不会感到惊讶,如果循环被丢弃的全部为好。

在衡量性能,使用真实code进行探查。

I have the following program and I am running it on VS 2010 Debug mode. To my surprise the empty for loop is taking more time than the for loop with addition statement. The time for empty for loop is 2371 ms and for addition for loop the time is 2043 ms. And I ran it several times and every single time empty for loop is faster. What is going on ?

#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;
}

解决方案

  1. Build your app with optimizations turned on.
  2. Use a better timing method than GetTickCount, e.g. QueryPerformanceCounter
  3. Detect context switches by measuring elapsed time often, and discarding abnormally large samples.

If you do the above, the two loops should take the same amount of time, since x is unused the compiler will likely just discard the statement entirely. Wouldn't be surprised if the loops were discarded in their entirety as well.

When measuring performance, use a profiler on real code.

这篇关于运行时间(空循环VS for循环用一条语句)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆