当前位置:  开发笔记 > 编程语言 > 正文

Lua - 以毫秒为单位的当前时间

如何解决《Lua-以毫秒为单位的当前时间》经验,为你挑选了5个好方法。

是否有一种常见的方式来获取当前时间或以毫秒为单位?

os.time(),但它只提供整秒.



1> waqas..:

我使用LuaSocket来获得更高的精度.

require "socket"
print("Milliseconds: " .. socket.gettime()*1000)

这当然会增加依赖性,但适合个人使用(例如,在基准测试脚本中).


请注意,至少有一个人声称在Windows上这种实现不够高分辨率:http://lua-users.org/wiki/HiResTimer

2> Valerio Schi..:

如果你想要进行基准测试,可以使用doc.clock所示的os.clock:

local x = os.clock()
local s = 0
for i=1,100000 do s = s + i end
print(string.format("elapsed time: %.2f\n", os.clock() - x))


然而,这不是毫秒,而是以1/100秒的精度工作.
如果您调用使用线程的C函数,这不会很好.而不是实际花费的时间,它报告所有线程花费的时间,作为总和

3> Kevlar..:

在标准C lua中,没有.除非您愿意自己修改lua解释器以使os.time使用您想要的分辨率,否则您将不得不安顿几秒钟.但是,这可能是不可接受的,如果您正在编写代码供其他人自己运行而不是像您可以完全控制环境的Web应用程序那样.

编辑:另一种选择是在C中编写自己的小DLL,用一个新函数扩展lua,它可以为你提供所需的值,并要求将dll随你的代码一起分发给任何人使用它.


DLL或.so等取决于系统... :-)

4> 小智..:

我在Windows上为lua做了一个合适的解决方案.我基本上做了Kevlar建议的,但是使用共享库而不是DLL.这已经使用cygwin进行了测试.

我写了一些lua兼容的C代码,将它编译成共享库(.so文件通过gg在cygwin中),然后使用package.cpath将其加载到lua中并且需要"".为方便起见,写了一个适配器脚本.以下是所有来源:

首先是C代码,HighResTimer.c

////////////////////////////////////////////////////////////////
//HighResTimer.c by Cody Duncan
//
//compile with:  gcc -o Timer.so -shared HighResTimer.c -llua5.1
//compiled in cygwin after installing lua (cant remember if I 
//   installed via setup or if I downloaded and compiled lua, 
//   probably the former)
////////////////////////////////////////////////////////////////
#include 

typedef unsigned __int64 u64;
double mNanoSecondsPerCount;

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"


int prevInit = 0;
int currInit = 0;
u64 prevTime = 0;
u64 currTime = 0;
u64 FrequencyCountPerSec;

LARGE_INTEGER frequencyTemp;
static int readHiResTimerFrequency(lua_State *L)
{
    QueryPerformanceFrequency(&frequencyTemp);
    FrequencyCountPerSec = frequencyTemp.QuadPart;
    lua_pushnumber(L, frequencyTemp.QuadPart);
    return 1;
}

LARGE_INTEGER timerTemp;
static int storeTime(lua_State *L)
{
    QueryPerformanceCounter(&timerTemp);

    if(!prevInit)
    {
        prevInit = 1;
        prevTime = timerTemp.QuadPart;
    }
    else if (!currInit)
    {
        currInit = 1;
        currTime = timerTemp.QuadPart;
    }
    else
    {
        prevTime = currTime;
        currTime = timerTemp.QuadPart;
    }

    lua_pushnumber(L, timerTemp.QuadPart);
    return 1;
}

static int getNanoElapsed(lua_State *L)
{
    double mNanoSecondsPerCount = 1000000000/(double)FrequencyCountPerSec;
    double elapsedNano = (currTime - prevTime)*mNanoSecondsPerCount;
    lua_pushnumber(L, elapsedNano);
    return 1;
}


int luaopen_HighResolutionTimer (lua_State *L) {

    static const luaL_reg mylib [] = 
    {
        {"readHiResTimerFrequency", readHiResTimerFrequency},
        {"storeTime", storeTime},
        {"getNanoElapsed", getNanoElapsed},
        {NULL, NULL}  /* sentinel */
    };

    luaL_register(L,"timer",mylib);

    return 1;
}

-

-

现在让我们在lua脚本HighResTimer.lua中加载它.

注意:我将HighResTimer.c编译为共享库Timer.so

#!/bin/lua
------------------------------------
---HighResTimer.lua by Cody Duncan
---Wraps the High Resolution Timer Functions in
---   Timer.so
------------------------------------

package.cpath = "./Timer.so"     --assuming Timer.so is in the same directory
require "HighResolutionTimer"    --load up the module
timer.readHiResTimerFrequency(); --stores the tickFrequency


--call this before code that is being measured for execution time
function start()
    timer.storeTime();
end

--call this after code that is being measured for execution time
function stop()
    timer.storeTime();
end

--once the prior two functions have been called, call this to get the 
--time elapsed between them in nanoseconds
function getNanosElapsed()
    return timer.getNanoElapsed();
end

-

-

最后,使用定时器TimerTest.lua.

#!/bin/lua
------------------------------------
---TimerTest.lua by Cody Duncan
---
---HighResTimer.lua and Timer.so must 
---   be in the same directory as 
---   this script.
------------------------------------

require './HighResTimer' 

start();
for i = 0, 3000000 do io.write("") end --do essentially nothing 3million times.
stop();

--divide nanoseconds by 1 million to get milliseconds
executionTime = getNanosElapsed()/1000000; 
io.write("execution time: ", executionTime, "ms\n");

注意:任何评论都是在将源代码粘贴到帖子编辑器之后编写的,所以从技术上来说这是未经测试的,但希望这些评论不会混淆.如果有的话,我一定会回来提供修复.



5> yurenchen..:
lua得到毫秒

os.time()

os.time()
return sec // only

posix.lock_gettime(CLK)

https://luaposix.github.io/luaposix/modules/posix.time.html#clock_gettime

require'posix'.clock_gettime(0)
return sec, nsec

linux/time.h // man clock_gettime

/*
 * The IDs of the various system clocks (for POSIX.1b interval timers):
 */
#define CLOCK_REALTIME                  0
#define CLOCK_MONOTONIC                 1
#define CLOCK_PROCESS_CPUTIME_ID        2
#define CLOCK_THREAD_CPUTIME_ID         3
#define CLOCK_MONOTONIC_RAW             4
#define CLOCK_REALTIME_COARSE           5
#define CLOCK_MONOTONIC_COARSE          6

socket.gettime()

http://w3.impa.br/~diego/software/luasocket/socket.html#gettime

require'socket'.gettime()
return sec.xxx

waqas


比较和测试

get_millisecond.lua

local posix=require'posix'
local socket=require'socket'

for i=1,3 do
    print( os.time() )
    print( posix.clock_gettime(0) )
    print( socket.gettime() )
    print''
    posix.nanosleep(0, 1) -- sec, nsec
end

产量

lua get_millisecond.lua
1490186718
1490186718      268570540
1490186718.2686

1490186718
1490186718      268662191
1490186718.2687

1490186718
1490186718      268782765
1490186718.2688

推荐阅读
重庆制造漫画社
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有