如何从Linux中的C获取以毫秒为单位的当前时间? [英] How to get the current time in milliseconds from C in Linux?

查看:706
本文介绍了如何从Linux中的C获取以毫秒为单位的当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I get the current time on Linux in milliseconds?

推荐答案

可以使用 POSIX clock_gettime 函数.

This can be achieved using the POSIX clock_gettime function.

在当前版本的POSIX中,gettimeofday标记为已过时.这意味着它可能会从该规范的将来版本中删除.鼓励应用程序编写者使用clock_gettime函数而不是gettimeofday.

In the current version of POSIX, gettimeofday is marked obsolete. This means it may be removed from a future version of the specification. Application writers are encouraged to use the clock_gettime function instead of gettimeofday.

这里是如何使用clock_gettime的示例:

Here is an example of how to use 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.

If your goal is to measure elapsed time, and your system supports the "monotonic clock" option, then you should consider using CLOCK_MONOTONIC instead of CLOCK_REALTIME.

这篇关于如何从Linux中的C获取以毫秒为单位的当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆