Benchmarking
With os.clock, you can compute (just about) the CPU time taken to execute a chunk of code.
1
local start = os.clock() -- save current CPU time
2
​
3
for i = 1, 100000 do
4
-- do something
5
end
6
​
7
print('Time taken: '.. (os.clock() - start) ..' seconds.')
Copied!
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:
1
do
2
local units = {
3
['seconds'] = 1,
4
['milliseconds'] = 1000,
5
['microseconds'] = 1000000,
6
['nanoseconds'] = 1000000000
7
}
8
​
9
function benchmark(unit, decPlaces, n, f, ...)
10
local elapsed = 0
11
local multiplier = units[unit]
12
for i = 1, n do
13
local now = os.clock()
14
f(...)
15
elapsed = elapsed + (os.clock() - now)
16
end
17
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))
18
end
19
end
Copied!
  • unit: Unit of time to show the result in ('seconds', 'milliseconds', 'microseconds', or 'nanoseconds')
  • decPlaces: Number of decimal places to use when showing the elapsed time
  • n: Number of times to run the function
  • f: Function to run
  • ...: Arguments passed to function f
Example of using it from the previous page:
1
local stringLen = string.len
2
local tostring = tostring
3
​
4
function f()
5
for i = 1, 10000 do
6
stringLen(tostring(i))
7
end
8
end
9
​
10
function f_2()
11
for i = 1, 10000 do
12
string.len(tostring(i))
13
end
14
end
15
​
16
benchmark('milliseconds', 2, 50, f)
17
benchmark('milliseconds', 2, 50, f_2)
Copied!
Output of the above:
1
Benchmark results:
2
- 50 function calls
3
- 868.86 milliseconds elapsed
4
- 17.38 milliseconds avg execution time.
5
Benchmark results:
6
- 50 function calls
7
- 874.66 milliseconds elapsed
8
- 17.49 milliseconds avg execution time.
Copied!
Last modified 2yr ago
Copy link