简易Lua性能分析工具

我作为学校作业的一部分刚开始接触Lua。我想知道是否有一种简单的方法来实现Lua的性能分析?我需要一些能够显示分配内存,正在使用的变量(无论其类型)等等的东西。

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

我也找到了Shinny,但我找不到任何关于如何让它工作的文档。

点赞
用户1442917
用户1442917

有几个可以使用的分析器,但是大多数针对执行时间(基于调试钩子)。

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

-- 要调试的代码从此处开始
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

-- 要调试的代码在此结束;重置钩子
debug.sethook()

-- 打印结果
for f,time in pairs(total) do
  print(("Function %s took %.3f seconds after %d calls"):format(f, time, calls[f]))
end
2013-03-31 21:48:37