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

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

问题描述

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

  //打印秒精确度

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

int main(void)
{
time_t now,later;
双秒;

时间(& now);
sleep(2);

时间(&以后);
秒= difftime(稍后,现在);

printf(%。f秒差,秒);
}

我该如何做到这一点?

首先阅读时间(7) 手册页。然后,您可以使用 clock_gettime(2)系统调用(您可能需要链接 -lrt 才能得到它)。



所以你可以试试

pre $ 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花费了大约.5f秒\\\

((double)tend.tv_sec + 1.0e-9 * tend.tv_nsec) -
((double)tstart .tv_sec + 1.0e-9 * tstart.tv_nsec));

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


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?

解决方案

Read first the time(7) man page.

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

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

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

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