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

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

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

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

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

谢谢


当前回答

    #include<time.h>
    #include<stdio.h>
    int main(){
      clock_t begin=clock();

      int i;
      for(i=0;i<100000;i++){
        printf("%d",i);
      }
      clock_t end=clock();

      printf("Time taken:%lf",(double)(end-begin)/CLOCKS_PER_SEC);
    }

这个程序会很有效。

其他回答

Thomas Pornin的回答是:

#define TICK(X) clock_t X = clock()
#define TOCK(X) printf("time %s: %g sec.\n", (#X), (double)(clock() - (X)) / CLOCKS_PER_SEC)

像这样使用它:

TICK(TIME_A);
functionA();
TOCK(TIME_A);

TICK(TIME_B);
functionB();
TOCK(TIME_B);

输出:

time TIME_A: 0.001652 sec.
time TIME_B: 0.004028 sec.

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

$ time ./a.out

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

很多答案都建议使用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<time.h>
    #include<stdio.h>
    int main(){
      clock_t begin=clock();

      int i;
      for(i=0;i<100000;i++){
        printf("%d",i);
      }
      clock_t end=clock();

      printf("Time taken:%lf",(double)(end-begin)/CLOCKS_PER_SEC);
    }

这个程序会很有效。

你想要这样:

#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));

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