我有一个C程序,目的是在几个处理器上并行运行。我需要能够记录执行时间(可以从1秒到几分钟不等)。我已经搜索了答案,但它们似乎都建议使用clock()函数,然后涉及计算程序所用的时钟数除以Clocks_per_second值。

我不确定Clocks_per_second值是如何计算的?

在Java中,我只是在执行前后以毫秒为单位获取当前时间。

C语言中也有类似的东西吗?我看了一下,但我似乎找不到比第二次分辨率更好的方法。

我也知道一个分析器将是一个选项,但我希望自己实现一个定时器。

谢谢


当前回答

如果你的程序使用GPU或者使用sleep(),那么clock() diff给出的持续时间小于实际持续时间。这是因为clock()返回CPU时钟滴答数。它只能用于计算CPU使用时间(CPU负载),而不能用于计算执行持续时间。我们不应该使用clock()来计算持续时间。在C语言中,我们仍然应该使用gettimeofday()或clock_gettime()来表示持续时间。

其他回答

很多答案都建议使用clock(),然后是time.h中的CLOCKS_PER_SEC。这可能是一个坏主意,因为这是我的/bits/time.h文件所写的:

/* ISO/IEC 9899:1990 7.12.1: <time.h>
The macro `CLOCKS_PER_SEC' is the number per second of the value
returned by the `clock' function. */
/* CAE XSH, Issue 4, Version 2: <time.h>
The value of CLOCKS_PER_SEC is required to be 1 million on all
XSI-conformant systems. */
#  define CLOCKS_PER_SEC  1000000l

#  if !defined __STRICT_ANSI__ && !defined __USE_XOPEN2K
/* Even though CLOCKS_PER_SEC has such a strange value CLK_TCK
presents the real value for clock ticks per second for the system.  */
#   include <bits/types.h>
extern long int __sysconf (int);
#   define CLK_TCK ((__clock_t) __sysconf (2))  /* 2 is _SC_CLK_TCK */
#  endif

因此,CLOCKS_PER_SEC可能定义为1000000,这取决于用于编译的选项,因此它似乎不是一个好的解决方案。

你想要这样:

#include <sys/time.h>

struct timeval  tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);

printf ("Total time = %f seconds\n",
         (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
         (double) (tv2.tv_sec - tv1.tv_sec));

请注意,这个度量单位是微秒,而不是秒。

(如果您的系统管理员更改了系统时间,或者您的时区有不同的冬季和夏季时间,这里就没有所有的答案。因此…)

在linux上使用:clock_gettime(clock_单调ic_raw, &time_variable); 如果系统管理员改变了时间,或者你生活在一个冬季和夏季不同的国家,等等,它不会受到影响。

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

#include <unistd.h> /* for sleep() */

int main() {
    struct timespec begin, end;
    clock_gettime(CLOCK_MONOTONIC_RAW, &begin);

    sleep(1);      // waste some time

    clock_gettime(CLOCK_MONOTONIC_RAW, &end);

    printf ("Total time = %f seconds\n",
            (end.tv_nsec - begin.tv_nsec) / 1000000000.0 +
            (end.tv_sec  - begin.tv_sec));

}

Man clock_gettime声明:

CLOCK_MONOTONIC
              Clock  that  cannot  be set and represents monotonic time since some unspecified starting point.  This clock is not affected by discontinuous jumps in the system time
              (e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP.

如果您正在使用Unix shell运行,则可以使用time命令。

$ time ./a.out

假设a.out作为可执行文件将为你提供运行这个程序所需的时间

ANSI C只指定秒精度时间函数。但是,如果您在POSIX环境中运行,则可以使用gettimeofday()函数,该函数提供自UNIX纪元以来经过的时间的微秒分辨率。

作为旁注,我不建议使用clock(),因为它在许多(如果不是所有?)系统上实现得很糟糕,而且不准确,此外,它只指程序在CPU上花费了多长时间,而不是程序的总生命周期,根据您的问题,我认为您想测量的是总生命周期。