简单的 Lua 分析 [英] Easy Lua profiling
问题描述
我刚刚开始使用 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屋!