美文网首页
C编程,得到两个时间点间的纳秒差

C编程,得到两个时间点间的纳秒差

作者: louyang | 来源:发表于2018-01-31 08:10 被阅读11次
    #include <stdio.h>
    #include <time.h>
    
    int main(void)
    {
        struct timespec ts1, ts2;
        char buff[100];
    
        timespec_get(&ts1, TIME_UTC);
        strftime(buff, sizeof buff, "%D %T", gmtime(&ts1.tv_sec));
        printf("Current time: %s.%09ld UTC\n", buff, ts1.tv_nsec);
    
        timespec_get(&ts2, TIME_UTC);
        strftime(buff, sizeof buff, "%D %T", gmtime(&ts2.tv_sec));
        printf("Current time: %s.%09ld UTC\n", buff, ts2.tv_nsec);
    
        long diff = (ts2.tv_sec - ts1.tv_sec) * 1000000000 + ts2.tv_nsec - ts1.tv_nsec;
        printf("Difference: %ld\n", diff);
    }
    

    编译运行

    $ gcc a.c && ./a.out
    Current time: 01/31/18 00:10:30.885944522 UTC
    Current time: 01/31/18 00:10:30.886031023 UTC
    Difference: 86501
    

    参考
    https://stackoverflow.com/questions/16275444/how-to-print-time-difference-in-accuracy-of-milliseconds-and-nanoseconds

    相关文章

      网友评论

          本文标题:C编程,得到两个时间点间的纳秒差

          本文链接:https://www.haomeiwen.com/subject/htoczxtx.html