如何准确的统计自己程序的运行时间?也许你马上会回答使用C语言集中的clock()函数。不过如果你的程序可能要运行很久,clock()还行吗?答案是否定的。因为clock()内部使用的是clock_t (long类型),在Windows下它所能表示的时间是大约三万五千分钟,不过在unix下最多只能计时35分钟。查看了一下boost提供的timer代码,里面也有这个限制,:(。
大家知道clock()计算的是cpu使用时间,而time()计算的是wall clock time。理论上使用clock要比time要更加准确,特别是有多个进程在多线程调度下。不过在需要对运行超长时间的程序来说,time()看来是比较有效的方法了。
#include <sys/times.h>
#include <unistd.h>
double getRunTime(){
struct tms current;
times(¤t);
double norm = (double)sysconf(_SC_CLK_TCK);
return(((double)current.tms_utime)/norm);
}
int main(){
double startTime = getRunTime();
/* do some job here */
double endTime = getRunTime();
printf("CPU Time = %f second/n", (endTime - startTime) );
return 0;
}
大家有什么建议吗?
本文探讨了如何准确地测量程序的运行时间,特别是在程序需要长时间运行的情况下。文章对比了使用clock()和time()函数的不同,并提供了使用time()来实现长时间运行程序计时的有效方法。





