有没有一种(简单的)方法来获取 Lua 表的内存使用情况?

发布于 2024-08-25 15:26:32 字数 73 浏览 5 评论 0原文

我想知道 Lua 表使用了多少内存 - 无需迭代表内容并计算使用情况。是否有 Lua 5.1 函数或第 3 方库可以帮助解决此问题。

I'd like to find out how much memory a Lua table is using - without iterating through the table contents and counting up the usage. Is there a Lua 5.1 function or 3rd party library that could help with this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

喵星人汪星人 2024-09-01 15:26:32

您可以通过在整个代码的适当位置(例如插入操作之前和之后)调用 collectgarbage("count")gcinfo() 来监控 Lua 的内存使用情况。没有简单的方法可以获取表格的大小。

You can monitor the memory usage of Lua by calling collectgarbage("count") or gcinfo() in the appropriate locations throughout the code (e.g. before and after insert operations). There's no trivial way to get the size of a table.

享受孤独 2024-09-01 15:26:32

没有用于此任务的函数。你为什么要这样做?你想达到什么目的?

There is no function for this task. Why do you want to do this? What are you trying to achieve?

尬尬 2024-09-01 15:26:32

不会像 this有帮助吗?

2016 更新:另请参阅:http://www.lua.org/wshop15/Musa2.pdf< /a>

Wouldn't something like this or this help?

2016 Update: see also: http://www.lua.org/wshop15/Musa2.pdf

感情洁癖 2024-09-01 15:26:32

你可以做这样的事情:

local pre = collectgarbage("count")
local table = {1, 2, 3, 4, 5}
local aft = collectgarbage("count")

local probablyTableSize = aft - pre
print(probablyTableSize)

但请注意,我不太确定这在普通测试环境之外是否准确,因为后台发生了很多事情。当我们声明 table 变量时,有可能添加/删除更多内存。

这可能是多余的,但在这种情况下您可以做的是获取多次尝试的平均值或中位数,然后看看会发生什么。

You could do something like this:

local pre = collectgarbage("count")
local table = {1, 2, 3, 4, 5}
local aft = collectgarbage("count")

local probablyTableSize = aft - pre
print(probablyTableSize)

Do note though, I am not too sure if this would be accurate outside of plain testing environments with a lot of things going on in the background. There is a slight chance that more memory was added/removed when we were declaring the table variable.

This may be redundant, but what you could do in that case would be to get the mean or the median of multiple attempts and see what happens.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文