lua - 简单的 Lua 分析

标签 lua profiling profiler

我刚开始使用 Lua 作为学校作业的一部分。我想知道是否有一种简单的方法可以为 Lua 实现分析?我需要显示分配的内存、使用中的变量(无论它们的类型如何)等的东西。

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

我还找到了 Shinny,但我找不到任何有关如何使其工作的文档。

最佳答案

有几个profilers available您可以检查,但大多数都以执行时间为目标(并且基于调试 Hook )。

要跟踪变量,您需要使用 debug.getlocaldebug.getupvalue (来自您的代码或调试 Hook )。

要跟踪内存使用情况,您可以使用 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

关于lua - 简单的 Lua 分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725744/

相关文章:

lua - 清理数据表单场景

javascript - 有没有好的网站性能分析工具? (前端)

android - 是否有适用于 Android 的开源分析器

java - 在 Java 中分析并发程序行为的特性

c - 以线程安全的方式将userdata放在lua栈中

c++ - Lua、C++,有没有比 lua_open() 更深入的介绍?

datetime - os.difftime(t2, t1) 的用途是什么,但 t2 - t1 未涵盖?

java - 使用英特尔 VTune Amplifier XE 2013 分析 Java 应用程序

java - 优化 Java 代码的技巧

python 线路分析器查看结果