We can always restore if we get back to it.
FFA5M5O2YK3ILOLH5IEGW6VEOOY7CI22MMW7B3HUCCNWNJRXXSMQC --[[@title lua-profiler@version 1.1@description Code profiling for Lua based code;The output is a report file (text) and optionally to a console or other logger.The initial reason for this project was to reduce misinterpretations of code profilingcaused by the lengthy measurement time of the 'ProFi' profiler v1.3;and then to remove the self-profiler functions from the output report.The profiler code has been substantially rewritten to remove dependence to the 'OO'class definitions, and repetitions in code;thus this profiler has a smaller code footprint and reduced execution time up to ~900% faster.The second purpose was to allow slight customisation of the output report,which I have parametrised the output report and rewritten.Caveats: I didn't include an 'inspection' function that ProFi had, also the RAMoutput is gone. Please configure the profiler output in top of the code, particularly thelocation of the profiler source file (if not in the 'main' root source directory).@authors Charles Mallah@copyright (c) 2018-2020 Charles Mallah@license MIT license@sample Output will be generated like this, all output here is ordered by time (seconds):`> TOTAL TIME = 0.030000 s`--------------------------------------------------------------------------------------`| FILE : FUNCTION : LINE : TIME : % : # |`--------------------------------------------------------------------------------------`| map : new : 301 : 0.1330 : 52.2 : 2 |`| map : unpackTileLayer : 197 : 0.0970 : 38.0 : 36 |`| engine : loadAtlas : 512 : 0.0780 : 30.6 : 1 |`| map : init : 292 : 0.0780 : 30.6 : 1 |`| map : setTile : 38 : 0.0500 : 19.6 : 20963|`| engine : new : 157 : 0.0220 : 8.6 : 1 |`| map : unpackObjectLayer : 281 : 0.0190 : 7.5 : 2 |`--------------------------------------------------------------------------------------`| ui : sizeCharLimit : 328 : ~ : ~ : 2 |`| modules/profiler : stop : 192 : ~ : ~ : 1 |`| ui : sizeWidthToScreenWidthHalf : 301 : ~ : ~ : 4 |`| map : setRectGridTo : 255 : ~ : ~ : 7 |`| ui : sizeWidthToScreenWidth : 295 : ~ : ~ : 11 |`| character : warp : 32 : ~ : ~ : 15 |`| panels : Anon : 0 : ~ : ~ : 1 |`--------------------------------------------------------------------------------------The partition splits the notable code that is running the slowest, all other code is runningtoo fast to determine anything specific, instead of displaying "0.0000" the script will tidythis up as "~". Table headers % and # refer to percentage total time, and function call count.@example Print a profile report of a code block`local profiler = require("profiler")`profiler.start()`-- Code block and/or called functions to profile --`profiler.stop()`profiler.report("profiler.log")@example Profile a code block and allow mirror print to a custom print function`local profiler = require("profiler")`function exampleConsolePrint()` -- Custom function in your code-base to print to file or console --`end`profiler.attachPrintFunction(exampleConsolePrint, true)`profiler.start()`-- Code block and/or called functions to profile --`profiler.stop()`profiler.report("profiler.log") -- exampleConsolePrint will now be called from this@example Override a configuration parameter programmatically; insert your override values into anew table using the matched key names:`local overrides = {` fW = 100, -- Change the file column to 100 characters (from 20)` fnW = 120, -- Change the function column to 120 characters (from 28)` }`profiler.configuration(overrides)]]--[[ Configuration ]]--local config = {outputFile = "profiler.lua", -- Name of this profiler (to remove itself from reports)emptyToThis = "~", -- Rows with no time are set to this valuefW = 20, -- Width of the file columnfnW = 28, -- Width of the function name columnlW = 7, -- Width of the line columntW = 7, -- Width of the time taken columnrW = 6, -- Width of the relative percentage columncW = 5, -- Width of the call count columnreportSaved = "> Report saved to: ", -- Text for the file output confirmation}--[[ Locals ]]--local module = {}local getTime = os.clocklocal string, debug, table = string, debug, tablelocal reportCache = {}local allReports = {}local reportCount = 0local startTime = 0local stopTime = 0local printFun = nillocal verbosePrint = falselocal outputHeader, formatHeader, outputTitle, formatOutput, formatTotalTimelocal formatFunLine, formatFunTime, formatFunRelative, formatFunCount, divider, nilTimelocal function deepCopy(input)if type(input) == "table" thenlocal output = {}for i, o in next, input, nil dooutput[deepCopy(i)] = deepCopy(o)endreturn outputelsereturn inputendendlocal function charRepetition(n, character)local s = ""character = character or " "for _ = 1, n dos = s..characterendreturn sendlocal function singleSearchReturn(inputString, search)for _ in string.gmatch(inputString, search) do -- luacheck: ignorereturn trueendreturn falseendlocal function rebuildColumnPatterns()local c = configlocal str = "s: %-"outputHeader = "| %-"..c.fW..str..c.fnW..str..c.lW..str..c.tW..str..c.rW..str..c.cW.."s|\n"formatHeader = string.format(outputHeader, "FILE", "FUNCTION", "LINE", "TIME", "%", "#")outputTitle = "%-"..c.fW.."."..c.fW..str..c.fnW.."."..c.fnW..str..c.lW.."s"formatOutput = "| %s: %-"..c.tW..str..c.rW..str..c.cW.."s|\n"formatTotalTime = "Total time: %f s\n"formatFunLine = "%"..(c.lW - 2).."i"formatFunTime = "%04.4f"formatFunRelative = "%03.1f"formatFunCount = "%"..(c.cW - 1).."i"divider = charRepetition(#formatHeader - 1, "-").."\n"-- nilTime = "0."..charRepetition(c.tW - 3, "0")nilTime = "0.0000"endlocal function functionReport(information)local src = information.short_srcif not src thensrc = "<C>"elseif string.sub(src, #src - 3, #src) == ".lua" thensrc = string.sub(src, 1, #src - 4)endlocal name = information.nameif not name thenname = "Anon"elseif string.sub(name, #name - 1, #name) == "_l" thenname = string.sub(name, 1, #name - 2)endlocal title = string.format(outputTitle, src, name,string.format(formatFunLine, information.linedefined or 0))local report = reportCache[title]if not report thenreport = {title = string.format(outputTitle, src, name,string.format(formatFunLine, information.linedefined or 0)),count = 0, timer = 0,}reportCache[title] = reportreportCount = reportCount + 1allReports[reportCount] = reportendreturn reportendlocal onDebugHook = function(hookType)local information = debug.getinfo(2, "nS")if hookType == "call" thenlocal funcReport = functionReport(information)funcReport.callTime = getTime()funcReport.count = funcReport.count + 1elseif hookType == "return" thenlocal funcReport = functionReport(information)if funcReport.callTime and funcReport.count > 0 thenfuncReport.timer = funcReport.timer + (getTime() - funcReport.callTime)endendend--[[ Functions ]]----[[Attach a print function to the profiler, to receive a single string parameter@param fn (function) <required>@param verbose (boolean) <default: false>]]function module.attachPrintFunction(fn, verbose)printFun = fnverbosePrint = verbose or falseend--[[Start the profiling]]function module.start()if not outputHeader thenrebuildColumnPatterns()endreportCache = {}allReports = {}reportCount = 0startTime = getTime()stopTime = nildebug.sethook(onDebugHook, "cr", 0)end--[[Stop profiling]]function module.stop()stopTime = getTime()debug.sethook()end--[[Writes the profile report to file (will stop profiling if not stopped already)@param filename (string) <default: "profiler.log"> [File will be created and overwritten]]]function module.report(filename)if not stopTime thenmodule.stop()endfilename = filename or "profiler.log"table.sort(allReports, function(a, b) return a.timer > b.timer end)local fileWriter = io.open(filename, "w+")local divide = falselocal totalTime = stopTime - startTimelocal totalTimeOutput = "> "..string.format(formatTotalTime, totalTime)fileWriter:write(totalTimeOutput)if printFun ~= nil thenprintFun(totalTimeOutput)endfileWriter:write(divider)fileWriter:write(formatHeader)fileWriter:write(divider)for i = 1, reportCount dolocal funcReport = allReports[i]if funcReport.count > 0 and funcReport.timer <= totalTime thenlocal printThis = trueif config.outputFile ~= "" thenif singleSearchReturn(funcReport.title, config.outputFile) thenprintThis = falseendendif printThis then -- Remove lines that are not neededif singleSearchReturn(funcReport.title, "[[C]]") thenprintThis = falseendendif printThis thenlocal count = string.format(formatFunCount, funcReport.count)local timer = string.format(formatFunTime, funcReport.timer)local relTime = string.format(formatFunRelative, (funcReport.timer / totalTime) * 100)if not divide and timer == nilTime thenfileWriter:write(divider)divide = trueendif timer == nilTime thentimer = config.emptyToThisrelTime = config.emptyToThisend-- Build final linelocal output = string.format(formatOutput, funcReport.title, timer, relTime, count)fileWriter:write(output)-- This is a verbose print to the attached print functionif printFun ~= nil and verbosePrint thenprintFun(output)endendendendfileWriter:write(divider)fileWriter:close()if printFun ~= nil thenprintFun(config.reportSaved.."'"..filename.."'")endend--[[Modify the configuration of this module programmatically;Provide a table with keys that share the same name as the configuration parameters:@param overrides (table) <required> [Each key is from a valid name, the value is the override]@unpack config]]function module.configuration(overrides)local safe = deepCopy(overrides)for k, v in pairs(safe) doif config[k] == nil thenprint("error: override field '"..k.."' not found (configuration)")elseconfig[k] = vendendrebuildColumnPatterns()end--[[ End ]]--return module
-- https://github.com/2dengine/profile.lua-- "A small, non-intrusive module for finding bottlenecks in your Lua code."-- MIT licenselocal clock = os.clock--- Simple profiler written in Lua.-- @module profile-- @alias profilelocal profile = {}-- function labelslocal _labeled = {}-- function definitionslocal _defined = {}-- time of last calllocal _tcalled = {}-- total execution timelocal _telapsed = {}-- number of callslocal _ncalls = {}-- list of internal profiler functionslocal _internal = {}--- This is an internal function.-- @tparam string event Event type-- @tparam number line Line number-- @tparam[opt] table info Debug info tablefunction profile.hooker(event, line, info)info = info or debug.getinfo(2, 'fnS')local f = info.func-- ignore the profiler itselfif _internal[f] or info.what ~= "Lua" thenreturnend-- get the function name if availableif info.name then_labeled[f] = info.nameend-- find the line definitionif not _defined[f] then_defined[f] = info.short_src..":"..info.linedefined_ncalls[f] = 0_telapsed[f] = 0endif _tcalled[f] thenlocal dt = clock() - _tcalled[f]_telapsed[f] = _telapsed[f] + dt_tcalled[f] = nilendif event == "tail call" thenlocal prev = debug.getinfo(3, 'fnS')profile.hooker("return", line, prev)profile.hooker("call", line, info)elseif event == 'call' then_tcalled[f] = clock()else_ncalls[f] = _ncalls[f] + 1endend--- Sets a clock function to be used by the profiler.-- @tparam function func Clock function that returns a numberfunction profile.setclock(f)assert(type(f) == "function", "clock must be a function")clock = fend--- Starts collecting data.function profile.start()if rawget(_G, 'jit') thenjit.off()jit.flush()enddebug.sethook(profile.hooker, "cr")end--- Stops collecting data.function profile.stop()debug.sethook()for f in pairs(_tcalled) dolocal dt = clock() - _tcalled[f]_telapsed[f] = _telapsed[f] + dt_tcalled[f] = nilend-- merge closureslocal lookup = {}for f, d in pairs(_defined) dolocal id = (_labeled[f] or '?')..dlocal f2 = lookup[id]if f2 then_ncalls[f2] = _ncalls[f2] + (_ncalls[f] or 0)_telapsed[f2] = _telapsed[f2] + (_telapsed[f] or 0)_defined[f], _labeled[f] = nil, nil_ncalls[f], _telapsed[f] = nil, nilelselookup[id] = fendendcollectgarbage('collect')end--- Resets all collected data.function profile.reset()for f in pairs(_ncalls) do_ncalls[f] = 0endfor f in pairs(_telapsed) do_telapsed[f] = 0endfor f in pairs(_tcalled) do_tcalled[f] = nilendcollectgarbage('collect')end--- This is an internal function.-- @tparam function a First function-- @tparam function b Second functionfunction profile.comp(a, b)local dt = _telapsed[b] - _telapsed[a]if dt == 0 thenreturn _ncalls[b] < _ncalls[a]endreturn dt < 0end--- Iterates all functions that have been called since the profile was started.-- @tparam[opt] number limit Maximum number of rowsfunction profile.query(limit)local t = {}for f, n in pairs(_ncalls) doif n > 0 thent[#t + 1] = fendendtable.sort(t, profile.comp)if limit thenwhile #t > limit dotable.remove(t)endendfor i, f in ipairs(t) dolocal dt = 0if _tcalled[f] thendt = clock() - _tcalled[f]endt[i] = { i, _labeled[f] or '?', _ncalls[f], _telapsed[f] + dt, _defined[f] }endreturn tendlocal cols = { 3, 29, 11, 24, 32 }--- Generates a text report.-- @tparam[opt] number limit Maximum number of rowsfunction profile.report(n)local out = {}local report = profile.query(n)for i, row in ipairs(report) dofor j = 1, 5 dolocal s = row[j]local l2 = cols[j]s = tostring(s)local l1 = s:len()if l1 < l2 thens = s..(' '):rep(l2-l1)elseif l1 > l2 thens = s:sub(l1 - l2 + 1, l1)endrow[j] = sendout[i] = table.concat(row, ' | ')endlocal row = " +-----+-------------------------------+-------------+--------------------------+----------------------------------+ \n"local col = " | # | Function | Calls | Time | Code | \n"local sz = row..col..rowif #out > 0 thensz = sz..' | '..table.concat(out, ' | \n | ')..' | \n'endreturn '\n'..sz..rowend-- store all internal profiler functionsfor _, v in pairs(profile) doif type(v) == "function" then_internal[v] = trueendendreturn profile