Skip to content

Commit 8351e24

Browse files
committed
Add os.monotonic to expose a monotonic timer.
`os.clock` uses libc's `clock` which measure "user + sys" time which is very rarely useful. This patch adds a new timer `os.monotonic` which returns a monotonic timer. On Linux, none of the monotonic timers is documented to do exactly what we would like: of those available, `MONOTONIC_RAW` seems the option least likely to produce misleading results, so we pick that.
1 parent ac822a1 commit 8351e24

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/loslib.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,20 @@ static int os_clock (lua_State *L) {
189189
}
190190

191191

192+
#include <sys/time.h>
193+
#include "llimits.h"
194+
static int os_monotonic (lua_State *L) {
195+
struct timespec ts;
196+
if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == 0) {
197+
double seconds = ts.tv_sec + ts.tv_nsec / 1e9;
198+
lua_pushnumber(L, cast_num(seconds));
199+
return 1;
200+
} else {
201+
exit(1);
202+
}
203+
}
204+
205+
192206
/*
193207
** {======================================================
194208
** Time/Date operations
@@ -409,6 +423,7 @@ static const luaL_Reg syslib[] = {
409423
{"execute", os_execute},
410424
{"exit", os_exit},
411425
{"getenv", os_getenv},
426+
{"monotonic", os_monotonic},
412427
{"remove", os_remove},
413428
{"rename", os_rename},
414429
{"setlocale", os_setlocale},

0 commit comments

Comments
 (0)