Skip to content

Instantly share code, notes, and snippets.

@Earu
Created October 10, 2024 13:06
Show Gist options
  • Save Earu/cfa782eb40432fc34ee2197ced2b5526 to your computer and use it in GitHub Desktop.
Save Earu/cfa782eb40432fc34ee2197ced2b5526 to your computer and use it in GitHub Desktop.
Dead simple profiler in Lua
local profiler = {
call_stack = {}, -- Stack to keep track of active function calls
timings = {}, -- Stores the total time spent in each function
call_counts = {} -- Stores how many times each function was called
}
local function get_time()
return os.clock()
end
local function profiler_hook(event)
local info = debug.getinfo(2, "nS")
if event == "call" then
local func_name = info.name or "[unnamed]"
local start_time = get_time()
-- Push the start time and function name onto the call stack
table.insert(profiler.call_stack, {func_name, start_time})
elseif event == "return" then
local end_time = get_time()
local call_info = table.remove(profiler.call_stack) -- Pop the call from the stack
if not call_info then return end
local func_name = call_info[1]
local start_time = call_info[2]
local time_spent = end_time - start_time
profiler.timings[func_name] = (profiler.timings[func_name] or 0) + time_spent
profiler.call_counts[func_name] = (profiler.call_counts[func_name] or 0) + 1
end
end
function profiler.start()
debug.sethook(profiler_hook, "cr") -- Hook on 'call' and 'return' events
end
function profiler.stop()
debug.sethook()
end
function profiler.report()
local report = {}
for func_name, time_spent in pairs(profiler.timings) do
table.insert(report, { func_name = func_name, time_spent = time_spent, call_count = profiler.call_counts[func_name] or 0 })
end
table.sort(report, function(a, b) return a.time_spent > b.time_spent end)
-- Reset
profiler = {
call_stack = {},
timings = {},
call_counts = {}
}
print("Function Profiling Report:")
print("-----------------------------------")
for _, report_data in ipairs(report) do
print(string.format("Function: %s | Time: %.6f s | Calls: %d", report_data.func_name, report_data.time_spent, report_data.call_count))
end
print("-----------------------------------")
end
profiler.start()
timer.Simple(10, function()
profiler.stop()
profiler.report()
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment