如何记录每次插入输入时程序的运行时间?我尝试了这种特殊方法:
clock_t tStart = clock(),tEnd;
打印输出后:
tEnd = clock();
printf("Time taken: %.6fs\n", (double)(tEnd - tStart) / CLOCKS_PER_SEC);
但是,我有时在计算毫秒时最终会出现一堆0。有什么方法可以改善这个问题吗?
有什么方法可以改善这个问题吗?
如果您没有更好的计时器,如 jspcal 的答案中所建议的,那么另一种解决方案是多次重复相同的操作,然后将经过的时间除以重复次数:
const int REPS = 10000;
clock_t tStart = clock(),tEnd;
for (int i = 0; i < REPS; i++) {
// do your work here
}
tEnd = clock();
double time = (double)(tEnd - tStart)/REPS;
printf("Time taken: %.6fs\n", time / CLOCKS_PER_SEC);
也许尝试您的平台上可能提供的更高分辨率的计时器:
Linux: clock_gettime(CLOCK_REALTIME, &timeSpec)
Windows: QueryPerformanceCounter(&performanceCount)
在unix中,使用
time
,它分叉并执行程序,并在子进程退出后执行get_rusage()
。
因此,您不必对程序本身进行检测。
plasser@pisbak:$ time ./a.out omg.dat
real 0m10.276s
user 0m9.986s
sys 0m0.291s
plasser@pisbak:$