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

LLL*_*LLL 85 c linux posix

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

Dan*_*ing 93

这可以使用POSIXclock_gettime功能实现.

在POSIX的当前版本,gettimeofday标记为已过时.这意味着它可能会从规范的未来版本中删除.鼓励应用程序编写者使用该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);
}
Run Code Online (Sandbox Code Playgroud)

如果您的目标是测量经过的时间,并且您的系统支持"单调时钟"选项,那么您应该考虑使用CLOCK_MONOTONIC而不是CLOCK_REALTIME.

  • +1为POSIX正确 - 但你的答案有错误的单位.OP不希望时间_with_毫秒,但时间_in_毫秒. (5认同)
  • 很好的解决方案,但不要忘记你的`gcc`命令中的_-lm_. (5认同)
  • 根据round的联机帮助页,在将结果分配给整数(或long)时要使用lround (3认同)
  • @SamTebbs33 不应该有任何额外的毫秒。`spec.tv_nsec` 将始终小于 10 亿(因此舍入后 ms 永远不会超过 1000)。 (3认同)
  • 您需要使用 floor() 而不是 round() 以便它永远不会四舍五入到 1000 毫秒。否则,您将需要在发生这种情况时增加 `s`。可能是一个罕见的事件,但额外的数字可能会导致麻烦。 (2认同)

yad*_*dab 58

你必须做这样的事情:

struct timeval  tv;
gettimeofday(&tv, NULL);

double time_in_mill = 
         (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond
Run Code Online (Sandbox Code Playgroud)


Eri*_*ang 32

以下是获取当前时间戳的util函数,以毫秒为单位:

#include <sys/time.h>

long long current_timestamp() {
    struct timeval te; 
    gettimeofday(&te, NULL); // get current time
    long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
    // printf("milliseconds: %lld\n", milliseconds);
    return milliseconds;
}
Run Code Online (Sandbox Code Playgroud)

关于时区:

gettimeofday()支持指定时区,我使用NULL,忽略时区,但如果需要,可以指定时区.


@Update - 时区

由于long时间的表示与时区本身无关或受其影响,因此设置tzgettimeofday()的参数不是必需的,因为它不会产生任何差别.

并且,根据手册gettimeofday(),timezone结构的使用已经过时,因此tz通常应将参数指定为NULL,有关详细信息,请查看手册页.


Don*_*ows 12

使用gettimeofday()以获得秒和毫秒的时间.结合和舍入到毫秒是一个练习.


Cir*_*四事件 6

C11 timespec_get

它返回最多纳秒,四舍五入到实现的分辨率.

它已在Ubuntu 15.10中实现.API看起来与POSIX相同clock_gettime.

#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};
Run Code Online (Sandbox Code Playgroud)

更多细节:https://stackoverflow.com/a/36095407/895245