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

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

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

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

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

谢谢


当前回答

不是所有的解都在我的系统里起作用。

我可以适应

#include <time.h>

double difftime(time_t time1, time_t time0);

其他回答

很多答案都建议使用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,这取决于用于编译的选项,因此它似乎不是一个好的解决方案。

您必须考虑到,测量程序执行所花费的时间在很大程度上取决于机器在特定时刻的负载。

我们知道,在C语言中获取当前时间的方法有不同的方法,更简单的方法是:

#include <time.h>

#define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \
  ruse.ru_stime.tv_sec + 1e-6 * \
  (ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec))

int main(void) {
    time_t start, end;
    double first, second;

    // Save user and CPU start time
    time(&start);
    first = CPU_TIME;

    // Perform operations
    ...

    // Save end time
    time(&end);
    second = CPU_TIME;

    printf("cpu  : %.2f secs\n", second - first); 
    printf("user : %d secs\n", (int)(end - start));
}

希望能有所帮助。

的问候!

有些人可能会发现另一种输入方式很有用:我在大学课程中用NVidia CUDA进行gpgpu编程时学过这种测量时间的方法(课程描述)。它结合了在以前的文章中看到的方法,我只是简单地发布它,因为需求赋予它可信度:

unsigned long int elapsed;
struct timeval t_start, t_end, t_diff;
gettimeofday(&t_start, NULL);

// perform computations ...

gettimeofday(&t_end, NULL);
timeval_subtract(&t_diff, &t_end, &t_start);
elapsed = (t_diff.tv_sec*1e6 + t_diff.tv_usec);
printf("GPU version runs in: %lu microsecs\n", elapsed);

我认为你可以乘以1.0 / 1000.0来得到适合你需要的测量单位。

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

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

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

$ time ./a.out

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