Add timer module

pull/1/head
Bram van den Heuvel 2024-04-29 17:31:03 +02:00
parent 7b29f68ffa
commit 78fea8405c
2 changed files with 104 additions and 0 deletions

View File

@ -1,3 +1,10 @@
-- DEVELOPMENT ONLY: Timer module for debugging performance
local modpath = minetest.get_modpath(minetest.get_current_modname())
dofile(modpath.."/lua/timer.lua")
-- DEVELOPMENT ONLY: End of timer module
-- Local variables used for programming
local internal =
{ a = 0

97
lua/timer.lua Normal file
View File

@ -0,0 +1,97 @@
local internal = {
waypoints = {},
stats = {},
sessions = 0,
last = os.clock()
}
timer = {}
function timer.start()
internal.waypoints = {}
internal.now()
internal.sessions = internal.sessions + 1
end
function timer.checkpoint(name)
local now = os.clock()
table.insert(internal.waypoints, { name, internal.last, now })
internal.now()
end
function timer.stop()
local name_len = 0
for _, t in ipairs(internal.waypoints) do
local name = t[1]
local start = t[2]
local stop = t[3]
local stat = internal.stats[name]
if stat then
internal.stats[name] = stat + (stop - start)
else
internal.stats[name] = stop - start
end
name_len = math.max(name_len, name)
end
local h1 = "Task"
local h2 = "Time"
local h3 = "Time (avg)"
internal.log(
table.concat(
{ h1
, string.rep(" ", name_len - string.len(h1))
, " | "
, h2
, string.rep(" ", 8 - string.len(h2))
, " | "
, h3
}
, ""
)
)
internal.log(string.rep("-", name_len + 3 + 8 + 3 + 8))
for _, t in ipairs(internal.waypoints) do
local name = t[1]
local duration = tostring(math.round(1e3 * (t[3] - t[2])))
local avg_duration = tostring(math.round(1e3 * internal.stats[name] / internal.sessions))
internal.log(
table.concat(
{ name
, string.rep(" ", name_len - string.len(name))
, " | "
, string.rep(" ", 5 - string.len(duration))
, duration
, " ms | "
, string.rep(" ", 5 - string.len(avg_duration))
, avg_duration
, " ms"
}
, ""
)
)
end
end
-- Log text to the Minetest chat
function internal.log(text)
minetest.chat_send_all(os.time() .. " - " .. text)
end
function internal.now()
internal.last = os.clock()
end
internal.now()