Timeval结构使用

时间:2014-02-03 05:22:34

标签: c linux time gettime gettimeofday

我需要计算运行某个功能所需的时间并运行以下代码,记录和放大输出一段代码的执行时间,以纳秒为单位

之间也有什么区别

struct timeval timer_spent& timeval timer_spent

/* Put this line at the top of the file: */
#include <sys/time.h>

/* Put this right before the code you want to time: */
struct timeval timer_start, timer_end;
gettimeofday(&timer_start, NULL);

/* Put this right after the code you want to time: */
gettimeofday(&timer_end, NULL);
double timer_spent = timer_end.tv_sec - timer_start.tv_sec + (timer_end.tv_usec - timer_start.tv_usec);
printf("Time spent: %.6f\n", timer_spent)/1000000.0;

但我需要精确的时间,以纳秒为单位。我对timeval结构没有完全了解。

亲切地帮助我们...... !!

1 个答案:

答案 0 :(得分:5)

  

但我需要精确的时间,以纳秒为单位。

然后使用

int clock_gettime(clockid_t clk_id, struct timespec *tp);

以秒和纳秒为单位返回时间

struct timespec {
  time_t   tv_sec;        /* seconds */
  long     tv_nsec;       /* nanoseconds */
};

有用的链接: