2017-08-31 89 views
1

一个简单的C程序运行在Windows 10(Visual Studio中2013)C程序输出分析

#include <time.h> 

void hello(){ 
    printf("hello world"); 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    clock_t t; 
    for (int i = 0; i<50; i++){ 
     t = clock(); 
     hello(); 
     t = clock() - t; 
     double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds 

     printf("hello() took %f ms to execute \n", time_taken * 1000); 
    } 
    getchar(); 
    return 0; 
} 

输出:

hello worldhello() took 0.000000 ms to execute(35times) 
hello worldhello() took 17.000000 ms to execute 
hello worldhello() took 3.000000 ms to execute 
hello worldhello() took 2.000000 ms to execute 
hello worldhello() took 0.000000 ms to execute(5 times) 
hello worldhello() took 15.000000 ms to execute 
hello worldhello() took 0.000000 ms to execute(4 times) 
hello worldhello() took 16.000000 ms to execute 
hello worldhello() took 0.000000 ms to execute 

一些线是0.000000和一些线15.000000-17.000000

这些输出可能与第二次运行的输出不完全相同。但在第二/第三..运行必须有一些行包含0.000000ms和15.000000-17.000000ms。

  1. 0ms到16ms(是否为过程CPU时间?)。请你解释一下实际的原因。

  2. 如果我想避免这种变化,并得到像0-1毫秒一样的输出,那么我该如何更改我的代码。 (循环运行50次,但如果我运行的100或1000倍那么时间的影响可以很容易理解。)

+2

可能的重复[如何以毫秒分辨率获取Windows系统时间?](https://stackoverflow.com/questions/3729169/how-can-i-get-the-windows-system-time-with -millisecond分辨率)。 Windows时间戳和定时器的分辨率为16ms,除非您使用'timeBeginPeriod(1)'。为了计时,无论如何你应该使用'QueryPerformanceCounter'。如果您使用的是Windows 8或更新版本,并且需要精确的当前时间,请使用'GetSystemTimePreciseAsFileTime'。 – Groo

+0

我不认为'clock()'是非常准确的。试试'struct/time.h' –

+2

我希望你的计算机在从'printf()'返回之前执行其他内务处理任务。 –

回答

2

你的代码是太短clock()并没有要求的精度精确衡量的执行时间。添加到系统开销执行时钟测量,并且您得到随机结果。

为了获得更好的效果,请在函数上循环100万次,然后将时钟&除以100万以获得平均执行时间。

对于更复杂的程序,使用代码探查可能是一个更好的解决方案(其是专业的测量的当前功能的指令的执行时间,而不是一个简单的任务功能&细粒时钟)

1

1) 这是由于过程的频率不是恒定的。

所以当你通过一个循环打印时,它直接依赖于处理器的频率。

2)为了避免这种情况,您可以检查时钟值是否恰好超过1 ms或1 s,以便此时精确打印。 (在无限循环中)

1

我同意让 - 弗朗索瓦法布尔和本杰明奥代特。您可以使用google_benchmark来测试某段代码的性能。它将执行一个循环,以解决运行时差异。显示平均值和偏差。