This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Progercbsk's profile picture

Sleep() Performance

Started by Progercbsk, 18 November 2013 - 05:37 AM
Progercbsk #1
Posted 18 November 2013 - 06:37 AM
Hi,

in MP, our admin ask to avoid the "while true do … end" loop in our code, since it consumes server's cpu power. He ask to use triggering like os.pullEvent() etc…

I'm expecting to use the os.Sleep() in that kind of loop so it wont loads the server for nothing. Processing stuff once every 20 ticks is fair enough imo

while true do
  sleep(1)
  -- get datas
  -- process stuff
end

But in the wiki it says the implementation is like that :

function sleep( _nTime )
  local timer = os.startTimer( _nTime )
  repeat
	local sEvent, param = os.pullEvent( "timer" )
  until param == timer
end

So :
a) Is os.Sleep() making infinte loop loading cpu for nothing ? or
n) Can I safely assert that using os.Sleep() in an infinite loop doesnt load the server's cpu ?
Bomb Bloke #2
Posted 18 November 2013 - 08:40 AM
os.pullEvent() yields ("does nothing") until an event occurs. os.pullEvent( "timer" ) yields until a timer event specifically occurs. In this case, the repeat…until loop is there to make sure the timer that expires is the one that this sleep function itself started (as opposed to, say, a timer that you started somewhere else in your code).

While yielding, your program is not taxing the server. ComputerCraft will automatically terminate your script if it runs for more then ten seconds without yielding.

Quite a few commands yield automatically. Eg read(), or most turtle movement calls.