运行时间(空循环VS for循环用一条语句)语句、时间、VS、for

2023-09-11 06:47:57 作者:百毒不侵

我有以下的程序,我对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;
}
 

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

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

C语言分支和循环语句

在衡量性能,使用真实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;
}

解决方案

Build your app with optimizations turned on. Use a better timing method than GetTickCount, e.g. QueryPerformanceCounter 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.