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

#include 
#include 

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编程,得到两个时间点间的纳秒差)