首页 > 解决方案 > 无法获得正确的纳秒时间间隔

问题描述

我的代码无法捕获我的程序的正确运行时间。

我只想以纳秒为单位显示程序执行时间。我使用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。

标签: cpthreadsposix

解决方案


处理struct timespec容易出错。我建议始终将结果转换为clock_gettime64 位整数纳秒,然后才进行计算。例如:

#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;
}

推荐阅读