BeamMP / BeamMP-Server

Server for the multiplayer mod BeamMP for BeamNG.drive
https://beammp.com
GNU Affero General Public License v3.0
127 stars 53 forks source link

Add Lua execution profiler `Util.DebugExecutionTime()` #267

Closed lionkor closed 4 months ago

lionkor commented 8 months ago

Adds Util.DebugExecutionTime(), which returns a table of function_name: milliseconds, in which each function's execution time is averaged over all time.

You can call this function like so:

-- event to print the debug times
MP.RegisterEvent("printStuff", "printStuff")
-- prints the execution time of all event handlers
function printStuff()
    print(Util.DebugExecutionTime())
end
-- run every 5 seconds (or 10, or 60, whatever makes sense for you
MP.CreateEventTimer("printStuff", 5000)

Pretty print function:

function printDebugExecutionTime()
    local stats = Util.DebugExecutionTime()
    local pretty = "DebugExecutionTime:\n"
    local longest = 0
    for name, t in pairs(stats) do
        if #name > longest then
            longest = #name
        end
    end
    for name, t in pairs(stats) do
        pretty = pretty .. string.format("%" .. longest + 1 .. "s: %12f +/- %12f (min: %12f, max: %12f) (called %d time(s))\n", name, t.mean, t.stdev, t.min, t.max, t.n)
    end
    print(pretty)
end

Util.DebugExecutionTime() returns a table, where each key is an event handler function name, and each value is a table consisting of mean (simple average), stddev (standard deviation aka mean of the variance), min and max, all in milliseconds, as well as n as the number of samples taken.

lionkor commented 7 months ago

Now using a running calculation by using two running sums, which means we can get the mean and stdev over any number of samples.

lionkor commented 4 months ago

Carp has been testing this extensively