轻松进行Lua分析 [英] Easy Lua profiling

查看:62
本文介绍了轻松进行Lua分析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始与Lua一起做学校作业.我想知道是否有一种简单的方法来实现Lua的性能分析?我需要显示分配的内存,使用中的变量(无论它们的类型如何)等等的东西.

I just started with Lua as part of a school assignment. I'd like to know if there's an easy way to implement profiling for Lua? I need something that displays allocated memory, variables in use regardless of their type, etc.

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

I've been finding C++ solutions which I have been able to compile successfully but I don't know how to import them to the Lua environment.

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

I also found Shinny but I couldn't find any documentation about how to make it work.

推荐答案

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

There are several profilers available that you can check, but most of them target execution time (and are based on debug hook).

要跟踪变量,您将需要使用 debug.getlocal debug.getupvalue (通过您的代码或调试钩子).

To track variables, you will need to use debug.getlocal and debug.getupvalue (from your code or from debug hook).

要跟踪内存使用情况,可以使用 collectgarbage(count)(可能在 collectgarbage(collect)之后),但这只会告诉您正在使用的总内存.要跟踪单个数据结构,您可能需要遍历全局和局部变量并计算它们占用的空间量.您可以查看此讨论以获得一些指示和实现细节

To track memory usage you can use collectgarbage(count) (probably after collectgarbage(collect)), but this only tells you total memory in use. To track individual data structures, you may need traverse global and local variables and calculate the amount of space they take. You can check this discussion for some pointers and implementation details.

类似这样的东西将是跟踪函数调用/返回的最简单的探查器(请注意,您不应该相信它生成的绝对数,而只能相信相对数):

Something like this would be the simplest profiler that tracks function calls/returns (note that you should not trust absolute numbers it generates, only relative ones):

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

这篇关于轻松进行Lua分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆