Skip to content

Commit db5cdb1

Browse files
committed
Avoid gettimeofday() in expireIfNeeded() when possible.
When the key expires far in the future compared to the cached time in server.mstime, calling mstime(), that calls gettimeofday(), should not be very useful. Instead when we are near the expire, we want the additional precision. This commit is related to issue redis#2552.
1 parent 1200bba commit db5cdb1

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/db.c

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -862,7 +862,21 @@ int expireIfNeeded(redisDb *db, robj *key) {
862862
* only the first time it is accessed and not in the middle of the
863863
* script execution, making propagation to slaves / AOF consistent.
864864
* See issue #1525 on Github for more information. */
865-
now = server.lua_caller ? server.lua_time_start : mstime();
865+
if (server.lua_caller) {
866+
now = server.lua_time_start;
867+
} else {
868+
/* If this is not the Lua caller, we actually need to get the current
869+
* time. However gettimeofday(), which is called by mstime(), may be
870+
* expensive, so we try to use the cached time instead, as found in
871+
* server.mstime, which is not very accurate, but should usually be
872+
* in the range of +/- 100 milliseconds.
873+
*
874+
* If the time the key will expire seems to be much more in the future
875+
* compared to server.mstime, we use the server.mstime approximation.
876+
* Otherwise if we see the key is going to expire within two seconds
877+
* we fetch the actual time from the operating system. */
878+
now = (when - server.mstime > 2000) ? server.mstime : mstime();
879+
}
866880

867881
/* If we are running in the context of a slave, return ASAP:
868882
* the slave key expiration is controlled by the master that will

0 commit comments

Comments
 (0)