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

How to get execution time of c program?

我正在为我的 c 程序使用时钟函数来打印当前的执行时间 program.I 我得到了错误的时间 output.I 想要以秒、毫秒和微秒为单位显示时间。

#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 \n", 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

#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.

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

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

有关此主题的更多信息,请参阅 What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX?

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

#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\n", time_taken);
    return 0;
}

输出:

time program took 3.005133 seconds to execute