C Linux 中 C 查找耗时

标签 c performance

我必须计算函数完成所需的时间。 该函数在循环中调用,我想找出总时间。 通常时间非常短,以纳秒或微秒为单位。

为了找出耗时,我使用了函数 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/

相关文章:

android - 了解 ImageProcessing 代码

ios - dequeueReusableCellWithIdentifier 提供什么性能优势?

c# - 改善可感知的 WPF 应用程序启动时间

MySQL:远程客户端上的复杂查询是否比本地客户端上慢?

python - 在嵌套列表中查找大量数据python

c++ - 所有移动操作系统都支持 ANSI C/ISO C++吗?

c - strtok 用于 GPS 解析,无法识别字符串

C字符串问题

节点的C函数宏

performance - 为什么 MOVNTI 不更慢,在循环中重复存储到同一地址?