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

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

//Prints in accuracy of seconds #include  #include  int main(void) { time_t now, later; double seconds; time(&now); sleep(2); time(&later); seconds = difftime(later, now); printf("%.f seconds difference", seconds); } 

我怎么能做到这一点?

首先阅读时间(7)手册页。

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

所以你可以试试

  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)); 

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

来自C11的timespec_get

此函数返回最多纳秒,舍入到实现的分辨率。

示例来自: http : //en.cppreference.com/w/c/chrono/timespec_get :

 #include  #include  int main(void) { struct timespec ts; timespec_get(&ts, TIME_UTC); char buff[100]; strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec)); printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec); } 

输出:

 Current time: 02/18/15 14:34:03.048508855 UTC 

更多细节: https : //stackoverflow.com/a/36095407/895245