I need to optimise my game. I used the profiler to identify some script bottlenecks. The trouble is then identifying which part of a script is causing trouble. I whipped up a script that I could use to measure the time taken to execute each function of a script. My test seems to work, but I’m concerned about whether I’ve misunderstood or missed something that might muddle my results. Would appreciate someone looking this over to sense check it before I expand it / start using it.
The main script (I named it ‘brofiler’ ):
local M = {}
M.total_time = 0
M.segments = {}
function M.frame_init()
M.total_time = 0
M.segments = {}
end
function M.start_segment(segment)
if not M.segments[segment] then
M.segments[segment] = {total_time = 0}
end
M.segments[segment].current_start = socket.gettime()
end
function M.end_segment(segment)
if not M.segments[segment] then
return
end
local t = socket.gettime() - M.segments[segment].current_start
M.segments[segment].total_time = M.segments[segment].total_time + t
M.total_time = M.total_time + t
end
function M.frame_final()
for segment, table in pairs(M.segments) do
print("Segment: " .. segment .. " took " .. table.total_time .. " (" .. math.ceil(table.total_time / M.total_time * 10000) / 100 .. "%)")
end
end
return M
Test script to profile:
local brofiler = require "brofiler.brofiler"
function update(self, dt)
brofiler.frame_init()
brofiler.start_segment("short_loop")
for i=1,100000 do
math.random()
end
brofiler.end_segment("short_loop")
brofiler.start_segment("long_loop")
for i=1,1000000 do
math.random()
end
brofiler.end_segment("long_loop")
brofiler.frame_final()
end
Output seems to work:
DEBUG:SCRIPT: Segment: short_loop took 0.011999130249023 (12.97%)
DEBUG:SCRIPT: Segment: long_loop took 0.080535888671875 (87.04%)
Thanks!