如何在 Linux 中从 C 打印毫秒和纳秒精度的时间差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16275444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:49:05  来源:igfitidea点击:

How to print time difference in accuracy of milliseconds and nanoseconds from C in Linux?

clinuxgcctime

提问by kingsmasher1

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.

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

//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?

我怎样才能做到这一点?

采纳答案by Basile Starynkevitch

Read first the time(7)man page.

首先阅读time(7)手册页。

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

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

So you could try

所以你可以试试

    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\n",
           ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - 
           ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));

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_getresto query the resolution of some clock.

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