加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

简易Lua剖析

发布时间:2020-12-14 21:47:12 所属栏目:大数据 来源:网络整理
导读:我刚开始将Lua作为学校作业的一部分.我想知道是否有一种简单的方法来实现Lua的分析?我需要显示分配的内存,使用的变量,无论其类型如何等等. 我一直在寻找能够成功编译的C解决方案,但我不知道如何将它们导入到Lua环境中. 我也找到了Shinny,但我找不到任何关于
我刚开始将Lua作为学校作业的一部分.我想知道是否有一种简单的方法来实现Lua的分析?我需要显示分配的内存,使用的变量,无论其类型如何等等.

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

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

解决方法

您可以检查几个 profilers available,但大多数都是执行时间(并且基于调试挂钩).

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

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

像这样的东西将是跟踪函数调用/返回的最简单的分析器(请注意,您不应该信任它生成的绝对数字,只有相对的数字):

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读