您可以检查几种可用的分析器,但大多数分析器的目标执行时间(并且基于调试钩子).
要跟踪变量,您需要使用debug.getlocal和debug.getupvalue(从您的代码或调试钩子).
要跟踪您可以使用的内存使用情况collectgarbage(count)(可能在之后collectgarbage(collect)),但这只会告诉您正在使用的总内存.要跟踪单个数据结构,您可能需要遍历全局和局部变量并计算它们占用的空间量.您可以查看此讨论以获取一些指示和实现细节.
像这样的东西将是跟踪函数调用/返回的最简单的分析器(请注意,您不应该信任它生成的绝对数字,只有相对的数字):
local calls, total, this = {}, {}, {}
debug.sethook(function(event)
local i = debug.getinfo(2, "Sln")
if i.what ~= 'Lua' then return end
local func = i.name or (i.source..':'..i.linedefined)
if event == 'call' then
this[func] = os.clock()
else
local time = os.clock() - this[func]
total[func] = (total[func] or 0) + time
calls[func] = (calls[func] or 0) + 1
end
end, "cr")
-- the code to debug starts here
local function DoSomethingMore(x)
x = x / 2
end
local function DoSomething(x)
x = x + 1
if x % 2 then DoSomethingMore(x) end
end
for outer=1,100 do
for inner=1,1000 do
DoSomething(inner)
end
end
-- the code to debug ends here; reset the hook
debug.sethook()
-- print the results
for f,time in pairs(total) do
print(("Function %s took %.3f seconds after %d calls"):format(f, time, calls[f]))
end
Run Code Online (Sandbox Code Playgroud)