如何准确的统计自己程序的运行时间

来源:互联网 发布:强制卸载软件工具 编辑:程序博客网 时间:2024/05/12 18:46

如何准确的统计自己程序的运行时间?也许你马上会回答使用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(&current);   
 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;
}

大家有什么建议吗?