这可以使用 POSIX clock_gettime 函数来实现。 在当前版本的 POSIX 中, gettimeofday 被 标记为 obsolete 。这意味着它可能会从规范的未来版本中删除。鼓励应用程序编写者使用 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 。 原文由 Dan Moulding 发布,翻译遵循 CC BY-SA 4.0 许可协议
这可以使用 POSIX
clock_gettime
函数来实现。在当前版本的 POSIX 中,
gettimeofday
被 标记为 obsolete 。这意味着它可能会从规范的未来版本中删除。鼓励应用程序编写者使用clock_gettime
函数而不是gettimeofday
。以下是如何使用
clock_gettime
的示例:如果您的目标是测量经过的时间,并且您的系统支持“单调时钟”选项,那么您应该考虑使用
CLOCK_MONOTONIC
而不是CLOCK_REALTIME
。