为了测试程序的性能,我们常常需要使用计时函数。在c++中提供了多种实现计时的方式。下面主要说明gettimeofday和clock函数的使用。
gettimeofday获取的是当前精确时间(1970年1月1日到现在的时间),或者为执行计时,也可以称之为墙上时间。在程序执行之前获取一次时间,执行结束之后获取一次时间,两次时间之差就是程序真正的执行时间。
而clock为cpu的时间,其中包括用户代码,库函数,系统调用等消耗的时间,但是不包括cpu的空闲时间(进程切换,等待消息消耗的时间)。在多任务的系统中,在涉及到进程切换的时候,clock能获得某个单一进程在cpu中的执行时间。而gettimeofday只能获得从程序开始执行到程序执行结束的时间,其中可能包括进程被切换出去的时间。
两个函数的具体用法如下:
#include#include #include #include using namespace std; struct timeva l start1,end1; clock_t begin, finish; int main() { gettimeofday(&start1,NULL); begin = clock() ; //开始计时 int sum = 0; for(int i=0;i<1000000000;i++) { sum += i; } cout << sum << endl; gettimeofday(&end1,NULL); finish = clock(); //结束计时 double timeUse = end1.tv_sec - start1.tv_sec + (end1.tv_usec - start1.tv_usec)/1000000.0; cout << "the time of gettimeofday is " << timeUse << endl; //打印结果 timeUse = (double)(finish - begin) / CLOCKS_PER_SEC; cout << "the time of clock is " << timeUse << endl; //打印结果 return 0; }
执行结果
xiang@xiang:~/workspace/system_lib$ ./time -1243309312 the time of gettimeofday is 3.09654 the time of clock is 2.92明显看出gettimeofday的时间长于clock的时间,其中可能就包括了程序被切换出去的而等待的时间。
在并行程序记录时间的时候,为了获取从程序开始到程序运行结束的时间一般使用gettimeofday.