简体   繁体   English

在C中无法测量以秒为单位的执行时间

[英]Measuring execution time with clock in sec in C not working

I'm trying to measure execution time in C using clock() under linux using the following: 我正在尝试使用以下代码在Linux下使用clock()测量C中的执行时间:

#include <time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char const* argv[])
{
  clock_t begin, end;
  begin = clock();
  sleep(2);
  end = clock();
  double spent = ((double)(end-begin)) / CLOCKS_PER_SEC;
  printf("%ld %ld, spent: %f\n", begin, end, spent);
  return 0;
}

The output is: 输出为:

1254 1296, spent: 0.000042

The documentation says to divide the clock time by CLOCKS_PER_SEC to get the execution time in sec, but this seems pretty incorrect for a 2sec sleep . 该文档说,将时钟时间除以CLOCKS_PER_SEC可以得到以秒为单位的执行时间,但这对于2sec sleep似乎很不正确。

What's the problem? 有什么问题?

Sleeping takes almost no execution time. 睡眠几乎不需要执行时间。 The program just has to schedule its wakeup and then put itself to sleep. 该程序只需要安排其唤醒时间,然后使其进入睡眠状态。 While it's asleep, it is not executing. 处于睡眠状态时,它没有执行。 When it's woken up, it doesn't have to do anything at all. 唤醒后,它根本不需要执行任何操作。 That all takes a very tiny fraction of a second. 所有这些只需一秒钟的很小一部分。

It doesn't take more execution time to sleep longer. 不需要花费更多的执行时间就可以使睡眠时间更长。 So the fact that there's a 2 second period when the program is not executing has no effect. 因此,有2秒钟的时间未执行程序这一事实没有任何效果。

clock measures CPU time (in Linux at least). clock测量CPU时间(至少在Linux中)。 A sleeping process consumes no CPU time. 休眠进程不占用任何CPU时间。

If you want to measure a time interval as if with a stopwatch, regardless of what your process is doing, use clock_gettime with CLOCK_MONOTONIC . 如果您想像秒表一样测量时间间隔,无论您的过程在做什么,都可以将clock_gettimeCLOCK_MONOTONIC一起CLOCK_MONOTONIC

man clock() has the answer: man clock()有答案:

The clock() function returns an approximation of processor time used by the program.

Which clearly tells that clock() returns the processor time used by the program, not what you were expecting the total run time of the program which is typically done using gettimeofday . 它清楚地表明clock()返回程序使用的处理器时间,而不是您期望的程序总运行时间(通常使用gettimeofday完成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM