Time Module
#time.getNow number time.getNow()

Returns the current high-precision time as an int64.

This can be used in comparing between two high-precision time values.

#time.deltaTime number time.deltaTime()

Returns the deltaTime (amount of time in seconds [including fractions] since last cycle) for the current logic cycle.

This is the same as the value passed to every call of macro.main().

This is often useful for any calculations that you want based on time; for example if you were to calculate the movement of an object, you would want to multiply it's speed by the deltaTime to see how much distance it should have moved within this "frame." Doing this will "smooth out" the stutter that can be caused by a variable logic rate, and ensure that the object moves at the same rate across all computers.

#time.diff number time.diff(number t1) number time.diff(number t1, number t2)

Compares two high-precision time values (from time.getNow()) and returns the amount of time that has elapsed between them in seconds (including fractions).

If only 't1' is given, then it returns the time that has elapsed between 't1' and now.

Example:
local start = time.getNow(); system.rest(1000); -- Rests for approximately 1 second, but isn't exact -- These two calls are essentially the same local diff1 = time.diff(start); local diff2 = time.diff(time.getNow(), start);

One practical use of this function is calculating exactly how long it takes to run a function. By checking which of your functions are slow, you know which ones to focus optimization on. This is called 'profiling.'

Example:
function test(a, b, c, d) -- This servers no purpose other than being -- an example... don't think about it too much. return math.sqrt(a*a + (b^c) / d) ^ (b*a) * math.sqrt(d ^ a ^ c ^ b); end iterations = 1000000; local start = time.getNow(); for i = 1,iterations do test(math.random(512), math.random(50), math.random(65535), math.random(100)); end local finished = time.getNow(); local timePerRun = time.diff(finished, start) / iterations; printf("test() function takes ~%0.8f seconds to process.\n", timePerRun);

Page last updated at 2018-09-25 20:48:49


Copyright 2024