如何获取 Linux 上的当前时间(以毫秒为单位)?
这可以通过使用来实现POSIX clock_gettime功能。
在当前版本的 POSIX 中,gettimeofday
is 标记为过时。这意味着它可能会从规范的未来版本中删除。鼓励应用程序编写者使用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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)