首页 > 解决方案 > 打印执行时间,两位小数

问题描述

我正在使用以下函数来估计函数的执行时间(性能):

double print_time(struct timeval *start, struct timeval *end)
{
    double usec;
    usec = (end->tv_sec * 1000000 + end->tv_usec) - (start->tv_sec * 1000000 + start->tv_usec);
    return usec / 1000.0;
}

简单代码:

struct timeval start, end;
double t = 0.0;
gettimeofday(&start, NULL);
... //code
gettimeofday(&end, NULL);
t = print_time(&start, &end);
printf("%.2f", t);

为什么当我打印变量时,我会看到以这种方式格式化的时间:3.613.97?问题与这两点有关。第一点和第二点是什么意思?通常我总是只看到一个小数点来分隔数字。

标签: cperformancetime

解决方案


包括正确的标题:

#include <time.h>
#include <stdio.h>

在程序开始时:

clock_t starttime = clock();

在程序结束时:

printf("elapsed time: %.3f s\n", (float)(clock() - starttime) / CLOCKS_PER_SEC);

这适用于多个平台(包括带有 MinGW-w64 的 Windows),但计时器 ( CLOCKS_PER_SEC) 的分辨率可能因平台而异。

请注意,这测量的是应用程序使用的时钟周期,而不是开始和结束之间经过的时间。因此,虽然它不是一个精确的计时器,但它可以更好地了解您的程序实际运行所需的时间。


推荐阅读