简易Lua剖析

Raú*_*Roa 5 profiler lua profiling

我刚开始将Lua作为学校作业的一部分.我想知道是否有一种简单的方法来实现Lua的分析?我需要显示分配的内存,使用的变量,无论其类型如何等等.

我一直在寻找能够成功编译的C++解决方案,但我不知道如何将它们导入到Lua环境中.

我也找到了Shinny,但我找不到任何关于如何使其工作的文档.

Pau*_*nko 7

您可以检查几种可用的分析器,但大多数分析器的目标执行时间(并且基于调试钩子).

要跟踪变量,您需要使用debug.getlocaldebug.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)