ubuntu下程序计时方法

来源:互联网 发布:淘宝的商家编码是什么 编辑:程序博客网 时间:2024/05/16 14:53

秒的转换关系:

================
1秒=1000毫秒(ms);
1秒=1000000 微秒(μs);
1秒=1000000000 纳秒(ns);



gettimeofday()相关介绍

===============================

1:在linux下通常可用的精度最高的时间接口是gettimeofday,它返回一个timeval结构,其精度为us,即10-6 秒,大多数情况这个精度已经够用了。

2:使用C语言编写程序需要获得当前精确时间(1970年1月1日到现在的时间),或者为执行计时,可以使用gettimeofday()函数。


包含头文件与使用方法

#include <sys/time.h>int gettimeofday(struct timeval*tv, struct timezone *tz);
tv: 参数tv是保存获取时间结果的结构体;

tz: 参数tz用于保存时区结果。


struct timezone结构体

struct timezone{int tz_minuteswest;/*格林威治时间往西方的时差*/int tz_dsttime;/*DST 时间的修正方式*/}
struct timeval结构体
struct timeval{long int tv_sec; // 秒数long int tv_usec; // 微秒数}


它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间:
struct timeval tv_begin, tv_end;gettimeofday(&tv_begin, NULL);foo();gettimeofday(&tv_end, NULL);

一般情况下timezone 参数基本不使用,若不使用则传入NULL即可。

注意:

在使用多线程openMP时,使用gettimeofday测试程序运行时间,请不要使用time_t(该函数获取的时间是gettimeofday的两倍,具体原因未深究)。


两个使用time_t与gettimeofday的具体实例

==================================================

方法一:time_t

具体例子

#include<iostream>#include<time.h>using namespace std;void test(int n){int a=0;time_t start,finish;start=clock();for(int i=0;i<1000000000;i++){a=i+1;}finish=clock();cout<<n<<" Time="<<finish-start<<endl;}int main(){time_t start,finish;int j=0;start=clock();for(j=0;j<2;j++){test(j);}finish=clock();cout<<"Total Time="<<finish-start<<endl;return 0;}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

方法二:gettimeofday

#include<iostream>#include<sys/time.h>#include<unistd.h>using namespace std;void test(int n){int a=0;struct timeval tstart,tend;double timeUsed;gettimeofday(&tstart,NULL);for(int i=0;i<1000000000;i++){a=i+1;}gettimeofday(&tend,NULL);timeUsed=1000000*(tend.tv_sec-tstart.tv_sec)+tend.tv_usec-tstart.tv_usec;cout<<n<<" Time="<<timeUsed/1000<<" ms"<<endl;}int main(){struct timeval tstart,tend;double timeUsed;gettimeofday(&tstart,NULL);int j=0;for(j=0;j<2;j++){test(j);}gettimeofday(&tend,NULL);timeUsed=1000000*(tend.tv_sec-tstart.tv_sec)+tend.tv_usec-tstart.tv_usec;cout<<" Total Time="<<timeUsed/1000<<" ms"<<endl;return 0;}


两种方法的计时是有区别的,可参考另一篇博客上面介绍的具体区别《openMP多线程编程





关于 clock()、time()、clock_gettime()和gettimeofday()函数的用法和区别 

======================================================================================

clock()函数的精确度是10毫秒(ms)
times()函数的精确度是10毫秒(ms)
gettimofday()函数的精确度是微秒(μs)
clock_gettime()函数的计量单位为十亿分之一,也就是纳秒(ns)

具体可参考 references 2

References:

1:http://www.linuxeden.com/html/sysadmin/20130416/138249.html(Linux下的高精度时间获得与定时器)

2:http://blog.csdn.net/wind19/article/details/12975173

3: http://baike.baidu.com/link?url=PW2SLdn6db1frYcXKFM2unUHLQMNZlBhCGcnJJsMgZgC0tHblRbfD1GRHvt68BKkAQnDiwOSH3dOGsmRG3dP5K




0 0
原创粉丝点击