如何获取 Linux 上的当前时间(以毫秒为单位)?
最佳答案
这可以使用 POSIX clock_gettime
来实现功能。
在当前版本的 POSIX 中,gettimeofday
为 marked obsolete .这意味着它可能会从规范的 future 版本中删除。鼓励应用程序编写者使用 clock_gettime
函数而不是 gettimeofday
。
下面是一个如何使用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
。
https://stackoverflow.com/questions/3756323/