您的位置:首页 > 运维架构 > Linux

2009-07-03 19:48 在linux中如何获得微秒精度的时间?-转

2016-01-16 11:53 671 查看
使用C的<time.h>库函数是无法达到微秒级别的时间的,所以上网找了一下答案,原文如下:

------------------------

使用C语言进行计时,在用户空间中可以使用C语言函数gettimeofday 得到时间,它的调用格式是:

#include <sys/time.h> 

int gettimeofday(struct timeval *tv, struct timezone *tz); 

int settimeofday(const struct timeval *tv , const struct timezone *tz); 

结构timeval的定义为:

struct timeval {long tv_sec; /* 秒数 */long tv_usec; /* 微秒数 */};

可以看出,使用这种方式计时,[b]精度可达微秒,[/b]也就是10-6秒。进行计时的时候,我们需要前后调用两次gettimeofday,然后计算中间的差值:

gettimeofday( &start, NULL );

foo(); 

gettimeofday( &end, NULL );

timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec; 

timeuse /= 1000000;

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

补充:刚从我又查了一下C库函数手册。

Syntax:

#include <ctime> clock_t clock( void );

The clock() function returns the processor time since the program started, or - 1 if that information is unavailable. To convert the return value to seconds, divide it by CLOCKS_PER_SEC. (Note: if your compiler is POSIX compliant, then CLOCKS_PER_SEC
is always defined as 1000000.)


可见在符合POSIX标准的C编译器上,借助clock()函数也是可以获得微秒精度的时间值,但由于这样的代码依赖于编译器,所以不推荐使用。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: