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

如何获取 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/

相关文章:

python - 如何在 Python 中加入两个生成器?

python - Python Web 框架、WSGI 和 CGI​​ 如何组合在一起

linux - 我应该选择什么 : GTK+ or Qt?

python - 是否有可能 "hack"Python 的打印功能?

python - 如何使 python 命令行程序自动完成任意事物而不是解释器

python - 使用 PyCrypto AES 256 加密和解密

linux - 来自守护程序 : "Conflict ... already in use by c

installation - 如何从命令行正确设置 CMAKE_INSTALL_PREFIX

python - 检查字符串是否包含数字

python - Seaborn地 block 没有出现