notsanequarium/lib/benchmark.lua
2021-01-23 01:33:08 +03:00

88 lines
No EOL
1.9 KiB
Lua

local this = {}
local updateLimit = 50
local benchmarkingThings = {}
local latestBenchmark = {}
local doneBench = {}
local function shrt(num)
return math.floor(num * 10000) / 10000
end
this.update = function()
doneBench = {}
end
this.startBenchmark = function(name)
latestBenchmark[name] = love.timer.getTime()
end
this.stopBenchmark = function(name)
if not benchmarkingThings[name] then benchmarkingThings[name] = {} end
if doneBench[name] then
local tbl = benchmarkingThings[name]
tbl[#tbl] = tbl[#tbl] + love.timer.getTime() - latestBenchmark[name]
else
table.insert(benchmarkingThings[name], love.timer.getTime() - latestBenchmark[name])
end
doneBench[name] = true
if #benchmarkingThings[name] > updateLimit then table.remove(benchmarkingThings[name], 1) end
end
this.getAverage = function(name)
local things
if name then
things = benchmarkingThings[name]
else
things = {}
for key in pairs(this.benchmarks) do
for _,n in ipairs(benchmarkingThings[key]) do
table.insert(things, n)
end
end
end
local total = 0
for _,n in ipairs(things) do
total = total + n
end
return total / #things
end
this.renderBenchmark = function()
local font = love.graphics.getFont()
local result = ''
local rowNum = 0
local averages = {}
local max = 0
for n,_ in pairs(this.benchmarks) do
local average = this.getAverage(n)
max = math.max(average, max)
averages[n] = average
end
for n,_ in pairs(this.benchmarks) do
local average = averages[n]
result = result .. '\n' .. shrt(average) .. 'ms' .. ' ' .. n
rowNum = rowNum + 1
local yoff = rowNum * font:getHeight()
love.graphics.setColor(1, 1, 1, 0.7)
love.graphics.rectangle('fill', 0, yoff, average * 1/max * love.graphics.getWidth(), font:getHeight())
end
love.graphics.setColor(0, 0, 0)
love.graphics.print(result)
end
this.benchmarks = benchmarkingThings
return this