3

I thought Lua os.clock() returns times in second. But from the documentation here https://www.lua.org/pil/22.1.html, the example they have

local x = os.clock()
local s = 0
for i=1,100000 do s = s + i end
print(string.format("elapsed time: %.2f\n", os.clock() - x))

Is rounding the result to 2 decimal places. Is os.clock() returns second.ms?

Also running this in Lua gives

> print(os.clock())
0.024615

What are these decimal places?

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • 2
    It's the number of seconds of program operation, but it's not rounded to the nearest second. It has millisecond precision – avariant Jul 11 '19 at 18:59
  • @avariant So why are all of these posts on https://stackoverflow.com/questions/463101/lua-current-time-in-milliseconds saying Lua does not have ms precision and you need to implement it in C or something else? Seems like `os.clock()` is then natively supported and has ms resolution – Kousha Jul 11 '19 at 19:00
  • 2
    os.time and os.clock provide different functions. os.time returns the current time and does only have seconds precision. os.clock returns the elapsed time since you launched (I assume) the lua interpreter. So if you are benchmarking or coding a delay of some kind, you can use os.clock for tracking elapsed time millisecond precision but it won't give you the time of day – avariant Jul 11 '19 at 19:14

1 Answers1

2

os.clock and os.time are not the same sort of time.

os.time is dealing with "wall-clock time, the sort of time humans use.

os.clock is a counter reporting CPU time. The decimal number you get from os.clock is the number of seconds the CPU spent running the current task. The CPU time has no correlation to wall-clock time other than using the same base time units (seconds).

virullius
  • 939
  • 6
  • 17
  • 2
    In Lua `os.clock` reports `real time` not `cpu time` for a windows system. For Linux and OS X i believe it does report `cpu time`. – Nifim Jul 11 '19 at 19:18
  • wow, no kidding, I didn't know that. https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/clock?view=vs-2019 – virullius Jul 11 '19 at 19:26
  • @Nifim Not in my Windows system. It reports run-time. – tonypdmtr Jul 13 '19 at 06:59
  • 1
    @tonypdmtr `real-time` from the the start of the program If you are debugging hit a break point or the program becomes halted for any reason the time the program is not executing is still counted in `os.clock`, on a windows system. – Nifim Jul 13 '19 at 12:44