如何测量C中的时间?

sna*_*ile 41 c windows time winapi

我想知道一些代码块执行了多长时间.像这样的东西:

startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);
Run Code Online (Sandbox Code Playgroud)

怎么样?

KLe*_*ee1 64

您可以clocktime.h中使用该方法

例:

clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
Run Code Online (Sandbox Code Playgroud)

  • 注意`clock()`测量CPU时间,而不是挂钟时间(这可能是也可能不是你想要的). (14认同)
  • @caf虽然在Linux上是真的,但clock()实际上计算了Windows上的挂钟时间:http://msdn.microsoft.com/en-us/library/4e2ess30.aspx (3认同)
  • 注意:对于任何困惑的人来说,CLOCKS_PER_SEC 并不是您的 cpu 的时钟频率。 (2认同)

Ste*_*hen 18

您可以使用time.h库,特别是timedifftime函数:

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t start,end;
  double dif;

  time (&start);
  // Do some calculation.
  time (&end);
  dif = difftime (end,start);
  printf ("Your calculations took %.2lf seconds to run.\n", dif );

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

(示例改编自上面链接的difftime网页.)

请注意,这种方法只能给予值得准确的秒- time_t自记录秒UNIX纪元(1970年1月1日).


Iva*_*aev 7

有时需要测量天文时间而不是CPU 时间(尤其适用于Linux):

#include <time.h>

double what_time_is_it()
{
    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);
    return now.tv_sec + now.tv_nsec*1e-9;
}

int main() {
    double time = what_time_is_it();
    printf("time taken %.6lf\n", what_time_is_it() - time);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 5

标准 C 库提供了该time函数,如果您只需要比较秒,则该函数非常有用。不过,如果您需要毫秒精度,最便携的方法是调用timespec_get. 如果系统支持的话,它可以报出高达纳秒精度的时间。然而,调用它需要花费更多的精力,因为它涉及一个结构。下面的函数仅将结构转换为简单的 64 位整数。

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

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}
Run Code Online (Sandbox Code Playgroud)

与 不同的是clock,此函数返回一个 Unix 时间戳,因此它将正确计算阻塞函数(例如 )所花费的时间sleep。对于基准测试和实现考虑运行时间的延迟来说,这是一个有用的属性。