我有一个程序,打印两个不同实例之间的时间差,但它打印的精度是秒。我想以毫秒为单位打印,另一个以纳秒为单位打印。
//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);
}
我怎么才能做到呢?
请先阅读time(7)手册页。
然后,您可以使用clock_gettime(2)系统调用(您可能需要链接
所以你可以试试
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));
不要期望硬件定时器具有纳秒精度,即使它们提供纳秒分辨率。并且不要尝试测量小于几毫秒的持续时间:硬件不够可靠。您可能还想使用
此函数返回最多纳秒,四舍五入到实现的分辨率。
示例来自:http://en.cppreference.com/W/C/chrono/timespec_get:
#include <stdio.h>
#include <time.h>
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