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

#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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容