【问题标题】:C: measure time of operation in LinuxC: 在 Linux 中测量运行时间
【发布时间】:2020-04-11 23:01:34
【问题描述】:

我需要在 C 程序中测量时间。我用谷歌搜索了两个选项:gettimeofday()time() 系统调用。例如:

#include <time.h>

...

time_t start, end;
double seconds;

time(&start);

/* Run some complex algorithm  ... */

time(&end);
seconds = difftime(end, start);

或者

#include <sys/time.h>
...
struct timeval start, end;
double elapsed_time;

gettimeofday(&start, NULL);

/* Data processing */

gettimeofday(&end, NULL);

/* calculate time in ms. */
elapsed_time = (end.tv_sec - start.tv_sec) * 1000.0;
elapsed_time += (end.tv_usec - start.tv_usec) / 1000.0;

据我了解,第二种方法提供了更高的精度(毫秒/微秒),而第一种方法仅以秒为单位返回经过的时间。我说的对吗?

【问题讨论】:

  • 稍微偏离主题但相关,请查看 timercmp(3) 以了解对 struct timeval 值进行数学运算的最佳方法,因为在执行减法时存在细微的问题 - 查看 timersub( ) 特别是。

标签: c linux time system-calls


【解决方案1】:

是的,你的理解是正确的。

还有clock_gettime 提供纳秒级分辨率。 (它是否真的有纳秒精度取决于你的硬件。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2015-12-25
    • 2011-04-23
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多