I'm trying to measure time of my code execution with the os.time() function and display it with LOVE framework. But, to my surprise, the displayed times are changing... My code is:
function foo()
start_time = os.time()
<some code>
end_time = os.time()
elapsed_time = os.difftime(end_time-start_time)
love.graphics.print('start time: ' .. start_time .. 's', 12, 12)
love.graphics.print('end time: ' .. end_time .. 's', 12, 22)
love.graphics.print('time elapsed: ' .. elapsed_time .. 's', 12, 32)
end
When I leave the window with my graphics open the times are changing (start and end growing and the difference changes between 1 and 2) - so the first question is how does that happen if os.time() returns a number. And also - is that a good way to measure the execution time of my application?
start
and end
should always be growing, unless time stops, in which case we're all in trouble.
The delta between them will change as a function of how long <some code>
takes to execute.
os.time
typically returns the number of seconds from some arbitrary point in the past (usually 1/1/1970 00:00:00). That's not guaranteed (it's implemented in terms of C's time
function which makes no such guarantees). But it should definitely always be advancing, or it's not really giving you the time, right?
BTW, you're using difftime
wrong. You're supposed to pass it two values, and it gives you the difference between them. You're passing it one value. It should barf on this, but instead it appears to be returning the first value, which in your case accidentally works because you happen to be on a machine where difftime
is actually t2-t1. On other systems this can break. You should change the call to:
elapsed_time = os.difftime(end_time,start_time)