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

最佳答案

这可以使用 POSIX clock_gettime 函数来实现。

在当前版本的 POSIX 中, gettimeofdaymarked 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

关于c - 如何从 Linux 中的 C 获取当前时间(以毫秒为单位)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3756323/

10-14 14:19
查看更多