一个简单的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。
0ms到16ms(是否为过程CPU时间?)。请你解释一下实际的原因。
如果我想避免这种变化,并得到像0-1毫秒一样的输出,那么我该如何更改我的代码。 (循环运行50次,但如果我运行的100或1000倍那么时间的影响可以很容易理解。)
可能的重复[如何以毫秒分辨率获取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
我不认为'clock()'是非常准确的。试试'struct/time.h' –
我希望你的计算机在从'printf()'返回之前执行其他内务处理任务。 –