如何从Linux中的C中获取以毫秒为单位的当前时间?
如果您想要在命令行中输入内容,那么date +%H:%M:%S.%N
会为您提供纳秒级的时间。
不完全:问题标记为'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,详情请查看手册页。
> gettimeofday()支持指定时区,我使用NULL,它会忽略时区,但如果需要,您可以指定一个时区。 你错了。时区应仅通过调用localtime()来引入。 – 2017-11-04 02:55:08
@ vitaly.v.ch我做了一个测试,将'gettimeofday()'的'tz'参数传递为'&(struct timezone tz = {480,0})'不会得到任何警告,不会对结果产生任何影响,这是有道理的,因为时间的“长”表示与时区本身无关或影响,对吧? – 2017-11-05 06:33:03
没有理由做任何测试。 Linux内核没有关于时区的正确信息,同时也没有办法提供它。这是为什么tz参数是以非常特定的方式处理的原因。长期的代表并不重要。 – 2017-11-05 10:54:27
这可以通过使用clock_gettime
函数来实现。
在当前版本的POSIX中,gettimeofday
是marked 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
。
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 */
};
这是习惯在计算器上有你的问题的身体问题。 – msw 2010-09-20 23:48:31