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

问题描述:

如何在毫秒内获得Linux上的当前时间?如何从Linux中的C中获取以毫秒为单位的当前时间?

+19

这是习惯在计算器上有你的问题的身体问题。 – msw 2010-09-20 23:48:31

使用gettimeofday()来获得以秒和微秒为单位的时间。结合和舍入到毫秒作为练习。

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

+5

不完全:问题标记为'C',并要求以毫秒为单位的历元时间。 – pilcrow 2013-06-28 19:53:05

你必须做这样的事情:

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 

以下是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()支持spe cify时区, 我使用NULL,它会忽略时区,但您可以指定时区,如果需要的话。


@Update - 时区

由于时间的long表示是不相关的或由时区本身来实现,所以设置tz PARAM函数gettimeofday的()是没有必要的,因为它获得了没有任何区别。

而且,根据页的gettimeofday(),使用timezone结构已经过时,因此tz参数通常应被指定为NULL,详情请查看手册页。

+0

> gettimeofday()支持指定时区,我使用NULL,它会忽略时区,但如果需要,您可以指定一个时区。 你错了。时区应仅通过调用localtime()来引入。 – 2017-11-04 02:55:08

+0

@ vitaly.v.ch我做了一个测试,将'gettimeofday()'的'tz'参数传递为'&(struct timezone tz = {480,0})'不会得到任何警告,不会对结果产生任何影响,这是有道理的,因为时间的“长”表示与时区本身无关或影响,对吧? – 2017-11-05 06:33:03

+0

没有理由做任何测试。 Linux内核没有关于时区的正确信息,同时也没有办法提供它。这是为什么tz参数是以非常特定的方式处理的原因。长期的代表并不重要。 – 2017-11-05 10:54:27

这可以通过使用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

+5

+1是正确的 - 但你的答案有错误的单位。 OP不希望时间_with_毫秒,而是时间_in_毫秒。 – pilcrow 2013-06-28 19:50:51

+4

好的解决方案,但不要忘记你的'gcc'命令中的_ -lm_。 – 2014-06-02 08:58:09

+1

根据round的手册页,当将结果赋给一个整数(或long)时,你想要使用lround – hildred 2016-03-21 21:42:53

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