Redis源码分析,在C语言中将当前时间转化成毫秒微秒整数值


发布者 ourjs  发布时间 1575452725580
关键字 Redis  C 

Redis中有两个内置的函数mstime/ustime,能直接获取当前时间的整数值。

 

https://github.com/microsoftarchive/redis/blob/3.0/src/redis.c

 
/* Return the UNIX time in microseconds */
PORT_LONGLONG ustime(void) {
struct timeval tv;
PORT_LONGLONG ust;

gettimeofday(&tv, NULL);
ust = ((PORT_LONGLONG)tv.tv_sec)*1000000;
ust += tv.tv_usec;
return ust;
}

/* Return the UNIX time in milliseconds */
PORT_LONGLONG mstime(void) {
return ustime()/1000;
}

调用:

 serverLog(LL_NOTICE, "Redis mstime %lld", mstime());
serverLog(LL_NOTICE, "Redis ustime %lld", ustime());

输出结果:

[28768] 04 Dec 17:35:09.479 * Redis mstime 1575452109479
[28768] 04 Dec 17:35:09.480 * Redis ustime 1575452109480154

 

毫秒值可直接在JavaScript中初始化,如:

> new Date(1575452109479)
Wed Dec 04 2019 17:35:09 GMT+0800 (中国标准时间)