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

问题描述 投票:5回答:1

我正在使用我的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个回答
3
投票

与流行的看法相反,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()函数可能更精确,但可能并非在所有系统上都可用
  • Linux系统上可用的gettimeofday()系统调用
  • 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
© www.soinside.com 2019 - 2024. All rights reserved.