【问题标题】:Timeval struct usageTimeval 结构体的使用
【发布时间】:2014-02-26 12:24:18
【问题描述】:

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

还有和有什么区别

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 结构一无所知。

请大家帮帮我.. !!

【问题讨论】:

  • 如果您想分析您的代码,请使用gprof。或者,如果您熟悉 MATLAB,您可能会喜欢我的tictoc.h
  • @rmartinjak :我不熟悉 MATLAB 兄弟。这就是问题所在 :(

标签: c linux time gettime gettimeofday


【解决方案1】:

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

然后使用

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

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

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

有用的链接:

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 2016-01-24
    • 1970-01-01
    • 2014-01-16
    • 2011-09-21
    • 1970-01-01
    • 2012-04-27
    • 2012-11-06
    • 2017-06-19
    相关资源
    最近更新 更多