Lua 獲取毫秒ms和微秒
阿新 • • 發佈:2019-01-24
Lua自帶的os函式,os.time()只取到秒。網上搜索lua 毫秒都是要使用 luasocket,覺得真沒那個必要為了一個函式,用一套用不上的東西。試著寫了個擴充套件,程式碼如下。
C語言:
#include<stdio.h>
#include<sys/time.h>
#include<time.h>
#include<lua.h>
#include<lauxlib.h>
//微秒
staticintgetmicrosecond(lua_State *L){
struct timeval tv;
gettimeofday(&tv,NULL );
long microsecond = tv.tv_sec*1000000+tv.tv_usec;
lua_pushnumber(L, microsecond);
return 1;
}
//毫秒
staticintgetmillisecond(lua_State *L){
struct timeval tv;
gettimeofday(&tv,NULL);
long millisecond = (tv.tv_sec*1000000+tv.tv_usec)/1000;
lua_pushnumber(L, millisecond);
return 1;
}
int luaopen_usertime(lua_State *L){
luaL_checkversion(L);
luaL_Reg l[] = {
{"getmillisecond", getmillisecond},
{"getmicrosecond", getmicrosecond},
{ NULL, NULL },
};
luaL_newlib(L, l);
return 1;
}
編譯命令: cc -g -O2 -Wall -fPIC --shared usertime.c -o usertime.so
Lua呼叫:
local utime = require "usertime"
local microsecond = utime.getmicrosecond()
local millisecond = utime.getmillisecond()
print('microsecond',microsecond)
print('millisecond',millisecond)