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

Higher resolution time functions

Started by raineth, 11 February 2013 - 05:01 AM
raineth #1
Posted 11 February 2013 - 06:01 AM
I would love to have a way to measure the passage of time with greater resolution than the 50ms that os.clock() provides (due to os.clock() advancing on 20Hz server ticks.) I don't care whether it's possible to determine 'real world' time.

I have a few things I'd like to use this for, but perhaps the most generally useful one is determining the relative CPU usage of a few coroutines; for example:
[...]
event = { os.pullEventRaw() }
for _, task in pairs(task_table) do
  start_time = os.clock()
  result = { coroutine.resume(task.coroutine, unpack(event)) }
  task.cpu_time = task.cpu_time + (os.clock() - start_time)
  [...]
done
[...]
This example works, but task.cpu_time gains up to ±50ms of error on every iteration (every event in this case). The worst cases are:
  • The coroutine takes 49ms to run but os.clock() does not advance, causing the code to lose all 49ms and record 0.
  • The coroutine takes <1ms to run but os.clock() advances (CC computers do not run in lock step with server ticks), causing the code to record 50ms.
Cloudy #2
Posted 11 February 2013 - 06:23 AM
Nah. The time is based on server ticks - as it should be. Anything else just doesn't make sense in the Minecraft context.