c - 时间结构使用

标签 c linux time gettime gettimeofday

我需要计算运行某个函数所花费的时间,遇到了下面的代码,以纳秒为单位记录并输出一段代码的执行时间

还有什么区别

struct timeval timer_spenttimeval 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 结构没有完整的想法。

请大家帮帮我.. !!

最佳答案

But I need the precise timing in nanoseconds.

然后使用

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

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

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

有用的链接:

关于c - 时间结构使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21520206/

相关文章:

C - 从字符串的中间开始遍历

c - 通过结构进行测量并搜索最低,最高和平均温度

c - 如何编译 Linux C 程序在另一台 Linux 机器上运行?

r - 按时间间隔合并记录

java - 在Java中找不到符号时间

c - 这是刷新 C 输入流的正确方法吗?

linux - 任何用于 ARM9 的开源、快速的 H263 解码器库比 ffmpeg?

linux - 在 debian wheezy 上编译新内核

datetime - 将 MySQL 日期时间字符串转换为 time.Time 格式

C - 读()和写()