Lua 取毫秒,微秒

Lua自带的os函数,os.time()只取到秒。网上搜索lua 毫秒都是要使用 luasocket,以为真没那个必要为了一个函数,用一套用不上的东西。试着写了个扩展,代码以下。socket

C语言:函数

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <lua.h>
#include <lauxlib.h>

//微秒
static int getmicrosecond(lua_State *L) {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    long microsecond = tv.tv_sec*1000000+tv.tv_usec;
    lua_pushnumber(L, microsecond);
    return 1;
}

//毫秒
static int getmillisecond(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.soui

Lua调用:lua

local utime = require "usertime"

local microsecond = utime.getmicrosecond()
local millisecond = utime.getmillisecond()

print('microsecond',microsecond)
print('millisecond',millisecond)