From 588ed956b15ce2fd85929d39b9fe761fb0711988 Mon Sep 17 00:00:00 2001 From: Bram van den Heuvel Date: Mon, 29 Apr 2024 18:08:37 +0200 Subject: [PATCH] Clean timer code --- lua/timer.lua | 78 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 60 insertions(+), 18 deletions(-) diff --git a/lua/timer.lua b/lua/timer.lua index e23fe55..a6a3773 100644 --- a/lua/timer.lua +++ b/lua/timer.lua @@ -39,7 +39,7 @@ function timer.stop() internal.stats[name] = stop - start end - name_len = math.max(name_len, name) + name_len = math.max(name_len, string.len(name)) end local h1 = "Task" @@ -60,29 +60,22 @@ function timer.stop() ) ) - internal.log(string.rep("-", name_len + 3 + 8 + 3 + 8)) + internal.log_hr(name_len) 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" - } - , "" - ) + 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 @@ -90,8 +83,57 @@ 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()