【问题标题】:How to get execution time of c program?如何获取c程序的执行时间?
【发布时间】:2019-08-16 02:42:27
【问题描述】:

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

#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 程序显示相同的时间。

【问题讨论】:

标签: c time execution


【解决方案1】:

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

这是来自 C 标准的语言:

7.27.2.1 clock 函数

概要

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

说明

clock 函数确定使用的处理器时间。

退货

clock 函数返回实现对程序使用的处理器时间的最佳近似值,因为该实现定义的时代开始时仅与程序调用相关。要确定以秒为单位的时间,时钟函数返回的值应除以宏CLOCKS_PER_SEC 的值。如果使用的处理器时间不可用,则函数返回值(clock_t)(−1)。如果无法表示该值,则该函数返回一个未指定的值。

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

  • time() 函数,分辨率为 1 秒
  • 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 程序执行时间为 3.005133 秒

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 2021-06-20
    • 1970-01-01
    • 2011-10-26
    • 2019-02-13
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多