如何在毫秒内获得Linux上的当前时间?
发布于 2018-03-01 15:56:53
这是一个如何使用clock_gettime
的例子:
#define _POSIX_C_SOURCE 200809L
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
void print_current_time_with_ms (void)
{
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
if (ms > 999) {
s++;
ms = 0;
}
printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n",
(intmax_t)s, ms);
}
如果您的目标是测量已用时间,并且您的系统支持“单调时钟”选项,那么您应该考虑使用CLOCK_MONOTONIC
而不是CLOCK_REALTIME
。
发布于 2018-03-01 16:00:21
你值得这样试下,我反正觉得这种方法很好:
struct timeval tv;
gettimeofday(&tv, NULL);
double time_in_mill =
(tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond
https://stackoverflow.com/questions/-100003550
复制相似问题