ns_cavegen/lua/timer.lua

140 lines
2.8 KiB
Lua

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, string.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_hr(name_len)
for _, t in ipairs(internal.waypoints) do
local name = t[1]
internal.log_time(
name,
internal.to_ms(t[3] - t[2]),
internal.to_ms(internal.stats[name] / internal.sessions),
name_len
)
end
internal.log_hr(name_len)
internal.log_time("Total", internal.sum(), internal.sum_avg(), name_len)
end
-- Log text to the Minetest chat
function internal.log(text)
minetest.chat_send_all(os.time() .. " - " .. text)
end
function internal.log_hr(name_len)
internal.log(string.rep("-", name_len + 3 + 8 + 3 + 8))
end
function internal.log_time(header, time, time_avg, header_max_len)
local duration = tostring(time)
local duration_avg = tostring(time_avg)
internal.log(
table.concat(
{ header
, string.rep(" ", header_max_len - string.len(header))
, " | "
, string.rep(" ", 5 - string.len(duration))
, duration
, " ms | "
, string.rep(" ", 5 - string.len(duration_avg))
, duration_avg
, " ms"
}
, ""
)
)
end
function internal.now()
internal.last = os.clock()
end
function internal.sum()
local s = 0
for _, t in ipairs(internal.waypoints) do
s = s + (t[3] - t[2])
end
return internal.to_ms(s)
end
function internal.sum_avg()
local s = 0
for _, t in pairs(internal.stats) do
s = s + t
end
return internal.to_ms(s / internal.sessions)
end
function internal.to_ms(s)
return math.round(s * 1e3)
end
internal.now()