Created
July 8, 2016 18:33
-
-
Save enzzc/56343f164320fc295233a7579c9193bc to your computer and use it in GitHub Desktop.
Lua, get clock time in msecs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Usage: | |
$ cc -fPIC -c now.c -I/usr/include/luaX.Y -O3 | |
$ cc now.o -shared -o now.so | |
In Lua: | |
> now = require 'now' | |
> now.now_ms() | |
> print(now.now_ms()) | |
1466176843794 # Msecs elapsed since Unix epoch | |
*/ | |
#include <time.h> | |
#include <sys/time.h> | |
#include "lua.h" | |
#include "lauxlib.h" | |
#include "lualib.h" | |
static int now_ms(lua_State *L) { | |
struct timespec ts; | |
clock_gettime(CLOCK_REALTIME, &ts); | |
long s = ts.tv_sec; | |
long ns = ts.tv_nsec; | |
long ms = s * 1000; | |
ms += ns / 1000000; | |
lua_pushnumber(L, ms); | |
return 1; | |
} | |
static const struct luaL_Reg now[] = { | |
{"now_ms", now_ms}, | |
{NULL, NULL} | |
}; | |
int luaopen_now(lua_State *L) { | |
lua_newtable(L); | |
lua_pushcfunction(L, now_ms); | |
lua_setfield(L, -2, "now_ms"); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment