如何在 Linux 中从 C 打印毫秒和纳秒精度的时间差异? [英] How to print time difference in accuracy of milliseconds and nanoseconds from C in Linux?

查看:33
本文介绍了如何在 Linux 中从 C 打印毫秒和纳秒精度的时间差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个程序可以打印 2 个不同实例之间的时间差,但它的打印精度为秒.我想以毫秒为单位打印它,另一个以纳秒为单位.

I have this program which prints the time difference between 2 different instances, but it prints in accuracy of seconds. I want to print it in milliseconds and another in nanoseconds difference.

//Prints in accuracy of seconds

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

int main(void)
{
    time_t now, later;
    double seconds;

    time(&now);
    sleep(2);

    time(&later);
    seconds = difftime(later, now);

    printf("%.f seconds difference", seconds);
}

我怎样才能做到这一点?

How can I accomplish that?

推荐答案

先阅读时间(7) 手册页.

然后,您可以使用 clock_gettime(2) 系统调用(您可能需要链接 -lrt 以获取它).

Then, you can use clock_gettime(2) syscall (you may need to link -lrt to get it).

所以你可以试试

    struct timespec tstart={0,0}, tend={0,0};
    clock_gettime(CLOCK_MONOTONIC, &tstart);
    some_long_computation();
    clock_gettime(CLOCK_MONOTONIC, &tend);
    printf("some_long_computation took about %.5f seconds
",
           ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - 
           ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));

不要期望硬件计时器具有纳秒精度,即使它们提供纳秒分辨率.并且不要尝试测量小于几毫秒的持续时间:硬件不够忠实.您可能还想使用 clock_getres 来查询某个时钟的分辨率.

Don't expect the hardware timers to have a nanosecond accuracy, even if they give a nanosecond resolution. And don't try to measure time durations less than several milliseconds: the hardware is not faithful enough. You may also want to use clock_getres to query the resolution of some clock.

这篇关于如何在 Linux 中从 C 打印毫秒和纳秒精度的时间差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆