如何打印毫秒和纳秒的精度的时差? [英] How to print time difference in accuracy of milliseconds and nanoseconds?
问题描述
我有这个程序,打印2个不同的实例之间的时间差,但它在几秒钟准确性打印。我想打印在纳秒差异毫秒另一个。
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?
推荐答案
首先阅读时间( 7)手册页。
然后,您可以使用 clock_gettime(2)系统调用(您可能需要链接 -lrt
来得到它)。
Then, you can use clock_gettime(2) syscall (you may need to link -lrt
to get it).
所以,你可以尝试
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
来查询一些时钟的分辨率。
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.
这篇关于如何打印毫秒和纳秒的精度的时差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!