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

时间:2010-09-20 23:43:46

标签: c linux posix

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

8 个答案:

答案 0 :(得分:89)

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

在当前版本的POSIX中,gettimeofdaymarked obsolete。这意味着它可能会从规范的未来版本中删除。我们鼓励应用程序编写者使用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

答案 1 :(得分:56)

你必须做这样的事情:

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

答案 2 :(得分:29)

以下是获取当前时间戳的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;
}

关于时区

  

gettimeofday()支持指定时区,   我使用 NULL 来忽略时区,但如果需要,你可以指定一个时区。


@Update - timezone

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

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

答案 3 :(得分:13)

使用gettimeofday()获取以秒和微秒为单位的时间。结合和舍入到毫秒是一个练习。

答案 4 :(得分: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 */
};

此处有更多详情:https://stackoverflow.com/a/36095407/895245

答案 5 :(得分:0)

源自Dan Moulding的POSIX答案,这应该可以工作:

#include <time.h>
#include <math.h>

long millis(){
    struct timespec _t;
    clock_gettime(CLOCK_REALTIME, &_t);
    return _t.tv_sec*1000 + lround(_t.tv_nsec/1.0e6);
}

还有David Guyon指出的:用-lm编译

答案 6 :(得分:0)

此版本不需要数学库,并检查了clock_gettime()的返回值。

#include <time.h>
#include <stdlib.h>
#include <stdint.h>

/**
 * @return milliseconds
 */
uint64_t get_now_time() {
  struct timespec spec;
  if (clock_gettime(1, &spec) == -1) { /* 1 is CLOCK_MONOTONIC */
    abort();
  }

  return spec.tv_sec * 1000 + spec.tv_nsec / 1e6;
}

答案 7 :(得分:-1)

如果您要在命令行中输入内容,date +%H:%M:%S.%N将为您提供纳秒时间。