c - 打印执行时间,两位小数
问题描述
我正在使用以下函数来估计函数的执行时间(性能):
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
?问题与这两点有关。第一点和第二点是什么意思?通常我总是只看到一个小数点来分隔数字。
解决方案
包括正确的标题:
#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
) 的分辨率可能因平台而异。
请注意,这测量的是应用程序使用的时钟周期,而不是开始和结束之间经过的时间。因此,虽然它不是一个精确的计时器,但它可以更好地了解您的程序实际运行所需的时间。
推荐阅读
- javascript - 如何更改克隆表中的数据?
- python - KafkaConsumer 阻止其他 asyncio.Task 正常运行
- c - 收到警告“[-Wimplicit-int]”
- dart - 如何使用 Dart 正确创建安全的 Web 服务器?
- reactjs - 从组件库导入的组件样式在 ssr 期间未应用
- javascript - Javascript 刷新页面警报返回错误结果
- python - 为什么 Seaborn 线图“大小”论点最终成为传奇艺术家?
- android - Kotlinx 将 JSON Array 序列化为数据类
- swift - 如何从 NSSearchField 中删除选定/突出显示的字符串?(迅速)
- docker - Hyperledger Fabric 测试网络链码安装 Windows 10 上的错误 500