how to use os.difftime?

I am working on a game that needs to track the time from the start of a round to the conclusion of a round, and os.difftime seems like the most viable way to measure it (if you have a better way please share.) I can’t really figure out from what I have read how to set T1 and T2, and was wondering if someone could help me out. Thanks.

@jrohanian Here an example of how long it takes to do 10 million square root routines.


function setup()
    t1=os.time()
    for z=1,10000000 do
        a=math.sqrt(z)
    end
    t2=os.time()
    print(os.difftime(t2,t1))
end

@Jrohanian os.difftime(t2,t1) is the same as t2-t1. All it does is subtract t1 from t2.

@dave1707 , so you just set t1 and t2 to os.time when I want them?

@jrohanian Yes. Set t1 when you start, set t2 when you stop, and subtract t1 from t2 to get the difference in seconds. Or you can do something like this.


t1=os.time()    -- start time

... do whatever you want

diff=os.time()-t1

ok thanks

I would just recommend use ElapsedTime. os.time() only uses computing time, so it can be inaccurate when comparing times between large amounts of frames.

@dave1707 os.difftime actually isn’t startTime - endTime. On high precisions, I’ve found it produces odd results.

@SkyTheCoder os.time() returns the number of seconds from 12AM Jan 1, 1970. It uses the system clock, so it isn’t affected by slow FPS. When Codea used 32 bit math, the results weren’t accurate because the size of the seconds returned is 10 digits. Now that Codea uses 64 bit math, the time is correct. os.clock() uses CPU time and that isn’t accurate to use for timed results. As for os.difftime(t2,t1), that just subtracts t1 from t2 and returns the difference, so I’m not sure why you would get odd results. Maybe that was back when you were using 32 bit math.

@dave1707 Sorry, I got confused between os.time() and os.clock().

On the project where os.difftime was giving odd results, I was using os.clock() for the parameters (I think I confused the two back then, also). But it still wasn’t producing endTime - startTime. And it was running on Codea 2.0.