如何从Linux中的C获取当前时间(以毫秒为单位)?

新手上路,请多包涵

如何以毫秒为单位获取 Linux 上的当前时间?

原文由 LLL 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 555
1 个回答

这可以使用 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题