• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Benchmarking your code in Lua

Infernum

Senator
Joined
Feb 14, 2015
Messages
5,643
Solutions
559
Reaction score
3,949
Core code:
Lua:
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: %d function calls | %.'.. decPlaces ..'f %s elapsed | %.'.. decPlaces ..'f %s avg execution time.', n, elapsed * multiplier, unit, (elapsed / n) * multiplier, unit))
    end
end

How to run tests: Wrap the code you want to test inside of a function, and pass it to the benchmark function.

benchmark:
  • unit : Unit of time to view elapsed time in, see local units table for the list of units.
  • decPlaces : Number of decimal places for the elapsed time output
  • n : Number of times to run the function
  • f : The function to benchmark
  • ... : All arguments passed to function f

Lua:
function test(n)
    local t = {}
    for i = 1, n do
        t[i] = i
    end
end

benchmark('milliseconds', 2, 500, test, 10000) -- Benchmark results: 500 function calls | 254.96 milliseconds elapsed | 0.51 milliseconds avg execution time.
 
Back
Top