如何获得c程序的执行时间?

How to get execution time of c program?

我正在使用我的c程序的时钟功能来打印当前程序的执行时间。我输出错误的时间。我想以秒,毫秒和微秒显示时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main()
{
    clock_t start = clock();
    sleep(3);
    clock_t end = clock();
    double time_taken = (double)(end - start)/CLOCKS_PER_SEC; // in seconds

    printf("time program took %f seconds to execute
"
, time_taken);
    return 0;
}


time ./time
time program took 0.081000 seconds to execute
real    0m3.002s
user    0m0.000s
sys     0m0.002s

我预计输出大约3秒,但显示错误。
如你所知,如果我使用Linux命令时间运行此程序,我得到正确的时间,我想使用我的c程序显示相同的时间。


与流行的看法相反,clock()函数检索CPU时间,而不是经过的时钟时间,因为名称容易引起人们相信。

这是C标准的语言:

7.27.2.1 The clock function

Synopsis

1
2
#include <time.h>
clock_t clock(void);

Description

The clock function determines the processor time used.

Returns

The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC. If the processor time used is not available, the function returns the value (clock_t)(?1). If the value cannot be represented, the function returns an unspecified value.

要检索已用时间,您应该使用以下方法之一:

  • time()功能,分辨率为1秒
  • timespec_get()功能可能更精确,但可能并非在所有系统上都可用
  • Linux系统上可用的gettimeofday()系统调用
  • clock_gettime()功能。

请参阅UNIX中的wall-clock-time,user-cpu-time和system-cpu-time具体是什么? 有关此主题的更多信息。

这是使用gettimeoday()的修改版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>

int main() {
    struct timeval start, end;

    gettimeofday(&start, NULL);
    sleep(3);
    gettimeofday(&end, NULL);

    double time_taken = end.tv_sec + end.tv_usec / 1e6 -
                        start.tv_sec - start.tv_usec / 1e6; // in seconds

    printf("time program took %f seconds to execute
"
, time_taken);
    return 0;
}

输出:

1
time program took 3.005133 seconds to execute