我必须计算函数完成所需的时间。 该函数在循环中调用,我想找出总时间。 通常时间非常短,以纳秒或微秒为单位。
为了找出耗时,我使用了函数 gettimeofday()(使用 struct timeval)和clock_gettime()(使用 struct timespec)。
问题是 timeval 以秒为单位返回的时间是正确的,但以微秒为单位是错误的。 同样,timespec 返回的时间(以纳秒为单位)也是错误的。 从某种意义上说,它们与以秒为单位返回的时间不符,这是错误的。
对于clock_gettime(),我尝试了CLOCK_PROCESS_CPUTIME_ID和CLOCK_MONOTONIC。 使用clock()也没有帮助。
代码片段:
struct timeval funcTimestart_timeval, funcTimeEnd_timeval;
struct timespec funcTimeStart_timespec, funcTimeEnd_timespec;
unsigned long elapsed_nanos = 0;
unsigned long elapsed_seconds = 0;
unsigned long diffInNanos = 0;
unsigned long Func_elapsed_nanos = 0;
unsigned long Func_elapsed_seconds = 0;
while(...)
{
gettimeofday(&funcTimestart_timeval, NULL);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &funcTimeStart_timespec);
...
demo_func();
...
gettimeofday(&funcTimeEnd_timeval, NULL);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &funcTimeEnd_timespec);
elapsed_seconds = funcTimeEnd_timeval.tv_sec - funcTimestart_timeval.tv_sec;
Func_elapsed_seconds+= elapsed_seconds;
elapsed_nanos = funcTimeEnd_timespec.tv_nsec - funcTimeStart_timespec.tv_nsec;
Func_elapsed_nanos+ = elapsed_nanos;
}
printf("Total time taken by demo_func() is %lu seconds( %lu nanoseconds )\n", Func_elapsed_seconds, Func_elapsed_nanos );
Printf 输出:
Total time taken by demo_func() is 60 seconds( 76806787 nanoseconds )
看到以秒为单位的时间和以纳秒为单位的时间不匹配。
如何解决此问题或任何其他适当的方法来查找耗时?
最佳答案
您阅读过 time(7) 的文档吗?和 clock_gettime(2) ?请阅读两遍。
struct timespec
不应该同时表达两次。字段tv_sec
给出第二部分ts,字段tv_nsec
给出纳秒部分tn来表达< br/> 时间t = ts + 10-9 tn
我建议将其转换为 float ,例如
printf ("total time %g\n",
(double)Func_elapsed_seconds + 1.0e-9*Func_elapsed_nanos);
使用浮点更简单,通常精度足以满足大多数需要。否则,当您添加或减去struct timespec
时,您需要处理添加/减去的tv_nsec
字段总和/差为负或大于1000000000的情况....
关于C Linux 中 C 查找耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112839/