【发布时间】: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