Lua microseconds sleep

元气小坏坏 提交于 2019-12-11 03:54:05

问题


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.



来源:https://stackoverflow.com/questions/30451354/lua-microseconds-sleep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!