Lua microseconds sleep

2019-07-18 17:33发布

问题:

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)?

回答1:

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.



回答2:

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.



标签: lua sleep