Benchmarking
With os.clock, you can compute (just about) the CPU time taken to execute a chunk of code.
local start = os.clock() -- save current CPU time
for i = 1, 100000 do
-- do something
end
print('Time taken: '.. (os.clock() - start) ..' seconds.')By saving the time before starting the code and subtracting the before from the time after it executes, you get an approximate amount of seconds taken to execute that chunk of code.
Here's a benchmarking function to help with determining the performance of code:
do
local units = {
['seconds'] = 1,
['milliseconds'] = 1000,
['microseconds'] = 1000000,
['nanoseconds'] = 1000000000
}
function benchmark(unit, decPlaces, n, f, ...)
local elapsed = 0
local multiplier = units[unit]
for i = 1, n do
local now = os.clock()
f(...)
elapsed = elapsed + (os.clock() - now)
end
print(string.format('Benchmark results:\n - %d function calls\n - %.'.. decPlaces ..'f %s elapsed\n - %.'.. decPlaces ..'f %s avg execution time.', n, elapsed * multiplier, unit, (elapsed / n) * multiplier, unit))
end
endunit: Unit of time to show the result in ('seconds', 'milliseconds', 'microseconds', or 'nanoseconds')decPlaces: Number of decimal places to use when showing the elapsed timen: Number of times to run the functionf: Function to run...: Arguments passed to functionf
Example of using it from the previous page:
Output of the above:
Last updated