2

Ok, I need to wait (for instance) for 10 us in my lua script. Is there any way to do it?

For now I use this simple (non busy-waiting) function using socket:

function my_utils.sleep(sec)
    socket.select(nil, nil, sec)
end

but it seems its "sleep minimum" is milliseconds.

Example 1:

for x=0,2*math.pi,0.008 do
    misc.printus()
    misc.sleep(0.001)
end

Output:

0.022654
0.023654
0.024654
0.025654
0.026654
0.027654
0.028654
0.029654
0.030654
0.031654
0.032654
...

Not bad!

Example 2:

for x=0,2*math.pi,0.008 do
    misc.printus()
    misc.sleep(0.0001)
end

Output:

0.537089
0.537089
0.537089
0.537089
... --(lots of)
38089
0.538089
0.538089
0.538089
0.538089
0.538089
0.538089
... --(lots of)
0.538089
0.577091 -- (jumps over 0.04 second!)
0.577091
0.577091
0.577091
0.577091
... --(and so on)

Could someone give me some explanations (and about 0.04 second jump)?

J. Leeroy
  • 450
  • 1
  • 5
  • 17

2 Answers2

3

Lua uses the time service provided by the operating system. The available resolution is usually not very high and it's perceived as time jumps at Lua level.

Imagine a wall clock with minute resolution. It cannot be used to measure millisecond intervals.

dlask
  • 8,776
  • 1
  • 26
  • 30
  • That's correct. I ran some tests using C and I saw the same picture. I'm using Windows 7 now and as I think now, you cant get timer resolution more than 1 ms in Windows. – J. Leeroy May 26 '15 at 11:31
  • Well, there is a way to obtain high time precision on Windows (see http://stackoverflow.com/questions/1825720/c-high-precision-time-measurement-in-windows) but it is not portable and thus unavailable in Lua. – dlask May 26 '15 at 11:34
  • If you are comfortable writing and compiling C on Windows, writing a C library to access Window's high performance counter is very easy to do. – Matthew Burke May 29 '15 at 02:12
1

In addition to jitter from your operating system's time, lua uses a garbage collector to manage its memory, which will run periodically. While it runs, all other action is delayed (though the delay should be quite short). Depending on the amount of allocation in your program, it is quite possible that your code tripped on such a GC pause.

llogiq
  • 13,815
  • 8
  • 40
  • 72