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

8

我正在使用clock函数来打印当前程序的执行时间。但是输出的结果是错误的。我希望能够以秒,毫秒和微秒的形式显示时间。

#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命令time运行此程序,我得到了正确的时间,我想用我的c程序显示相同的时间。

3
尝试使用POSIX的clock_gettime()函数(https://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html)。 - pmg
祝你在微秒级精度方面好运。 - Weather Vane
有人能更新我的代码,以获取当前程序的正确执行时间吗? - raj123
我没有理解你的回答。你能否修改我的示例代码或提供带有所需输出的任何示例代码?谢谢@chqrlie - raj123
显示剩余2条评论
1个回答

9
与流行观点相反,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() 函数
  • 适用于Linux系统的 gettimeofday() 系统调用
  • clock_gettime() 函数。

有关此主题的更多信息,请参见UNIX中的墙钟时间,用户CPU时间和系统CPU时间是什么?

这里是一个使用gettimeofday()的修改版本:

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

输出:

程序执行花费了3.005133秒的时间

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接