Lua 获取毫秒ms和微秒

下载c文件编译的so文件:http://download.csdn.net/detail/zhukangle/9766221


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

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.so

Lua调用:


local utime = require "usertime"

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

print('microsecond',microsecond)
print('millisecond',millisecond)
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值