c - 无法获得正确的纳秒时间间隔
问题描述
我的代码无法捕获我的程序的正确运行时间。
我只想以纳秒为单位显示程序执行时间。我使用clock_monotonic 来计算时间。在我的代码中,我将命令用作 ./mr.py ./factorise_3_n | grep Time 这里 mr.py 是范围为 (0,5) 的 python 文件。这个 .py 帮助显示范围(0,5)
struct timespec start, finish;
long long int elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
factorise();
clock_gettime(CLOCK_MONOTONIC, &finish);
elapsed = (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("Time elapsed was %lld ns \n",elapsed);
return 0;
我预计程序的输出时间为 621191192 ns。经过的时间为 625507930 ns。经过的时间为 633012644 ns。经过的时间为 627173911 ns。经过的时间是 622051300 ns。
但输出是 Time elapsed was 0 ns。经过的时间为 0 ns。经过的时间为 0 ns。经过的时间为 0 ns。经过的时间为 0 ns。
解决方案
处理struct timespec
容易出错。我建议始终将结果转换为clock_gettime
64 位整数纳秒,然后才进行计算。例如:
#include <stdint.h>
#include <stdio.h>
#include <time.h>
uint64_t monotonic_now() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * UINT64_C(1000000000) + t.tv_nsec;
}
int main() {
uint64_t start = monotonic_now();
uint64_t finish = monotonic_now();
printf("%.9f seconds\n", (finish - start) * 1e-9);
return 0;
}
推荐阅读
- python - 如何从字典值中推断出一个单独的元素?
- typescript - 打字稿如何安全地将一个枚举转换为另一个?
- python - 熊猫,我怎样才能避免使用 iterrow (如何根据来自另一个数据帧的值将值分配给数据帧中的新列)
- wpf - 有什么方法可以“反转”转换器吗?
- java - 签入 tpl-if-tag,如果字符在 gxt 模板中是中文
- java - Mapbox React Native Turn By Turn Navigation ANR 问题
- php - 如何以编程方式设置间隔时间并在我的自定义模块 Drupal 8 中运行 cron?
- api - 是空手道支持 <= 运算符匹配
- c++ - 使用 Bazel 构建 TensorFlow
- javascript - 如何使用 ResizeObserver 观察多个元素?