获得以毫秒为单位的当前时间 [英] Getting the current time in milliseconds

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

问题描述

我如何在Linux上当前时间以毫秒为单位?

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

推荐答案

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

This can be achieved using the clock_gettime function.

在POSIX的当前版本中, gettimeofday的是<一个href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/gettimeofday.html#tag_16_222_07\">marked过时。这意味着它可以从规范的将来版本中删除。鼓励应用程序编写者使用 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

    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.

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

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