views:

4231

answers:

5

Hi, another Lua question: Is there a common way to get the current time in or with milliseconds? There is os.time(), but it only provides full seconds.

+8  A: 

In standard C lua, no. You will have to settle for seconds, unless you are willing to modify the lua interpreter yourself to have os.time use the resolution you want. That may be unacceptable, however, if you are writing code for other people to run on their own and not something like a web application where you have full control of the environment.

Edit: another option is to write your own small DLL in C that extends lua with a new function that would give you the values you want, and require that dll be distributed with your code to whomever is going to be using it.

Kevlar
DLL or .so, etc. Depends on system... :-)
PhiLho
+1  A: 

Kevlar is correct.

An alternative to a custom DLL is Lua Alien

Doug Currie
+7  A: 

I use LuaSocket to get more precision.

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

This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).

waqas
+1  A: 

You can use C function gettimeofday : http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html

Here C library 'ul_time', function sec_usec resides in 'time' global table and returns seconds, useconds. Copy DLL to Lua folder, open it with require 'ul_time'.

http://depositfiles.com/files/3g2fx7dij

qwer
+3  A: 

If you want to benchmark, you can use os.clock as shown by the doc:

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))
Valerio Schiavoni