使用自定义的Lua分配器来计算内存使用量,但其结果与collectgarbage('count')不同。
2012-4-16 5:9:14
收藏:0
阅读:162
评论:1
最近我尝试跟踪我们项目中的lua内存使用情况,然后我接触到了使用lua_Alloc自定义分配器来完成这个任务的想法。嗯,分配器代码看起来很简单,而且它似乎工作得很好。
但是,很快,这个小函数遇到了两个挑战:
1.它输出的结果与collectgarbage('count')给出的值相差很大;
2.假设当前的内存使用为M字节,然后我们输入一些nil引用并调用gc,内存使用率将大于M字节。例如:A return,B return,C return,...,collectgarbage()
好吧,我听说如果你正确使用lua,就不会有内存泄漏,所以我认为我在计算内存使用率时做错了什么。请帮我找出原因。谢谢。
下面是可编译的代码:
extern "C"
{
#include "lua.h"
#include <lauxlib.h>
#include <lualib.h>
};
#include <cstdio>
#include <string>
#include <cstdlib>
using namespace std;
struct Tracker
{
size_t m_usage;
}g_tracker;
void*
Allocator(void* ud, void* ptr, size_t osize, size_t nsize)
{
Tracker* pTracker = (Tracker*)ud;
void* pRet = NULL;
if( nsize == 0 )
{
pTracker->m_usage -= osize;
//printf("Free %d bytes; ", osize);
free(ptr);
}
else
{
pTracker->m_usage -= osize;
//printf("first Free %d bytes; ", osize);
pTracker->m_usage += nsize;
//printf("then alloc %d bytes; ", nsize);
pRet = realloc(ptr, nsize);
}
//printf("current usage: %d bytes\n", pTracker->m_usage);
return pRet;
}
int main()
{
lua_State* L = lua_newstate(Allocator, &g_tracker );
luaL_openlibs(L);
char buf[4096];
while(true)
{
fgets(buf, 4096, stdin);
if( strlen(buf) > 1 && 0 != luaL_dostring(L, buf) )
{
const char* errmsg = lua_tostring(L, -1);
printf("%s\n", errmsg);
}
printf("current usage: %d bytes \n", g_tracker.m_usage);
}
}
关于#2的输入序列:
press enter
current usage: 18867 bytes
a=nil; b=nil; c=nil;
current usage: 19311 bytes
collectgarbage()
current usage: 18900 bytes
d=nil; e=nil; f=nil;
current usage: 19345 bytes
collectgarbage()
current usage: 18900 bytes
collectgarbage()
current usage: 18900 bytes
for a = 1, 1000, 1 do b = nil end; collectgarbage()
current usage: 19206 bytes
collectgarbage()
current usage: 18900 bytes
for i = 1, 1000, 1 do X = {}; for j = 1, 1000, 1 do X[j] = j end ; X = nil; collectgarbage() ; end
current usage: 19391 bytes
collectgarbage()
current usage: 18900 bytes
原文链接 https://stackoverflow.com/questions/10161699
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
根据 Lua 文档所述,
collectgarbage('collect')
返回一个以 千字节(kilobytes) 为单位的值,其中 1KB 等于 1024 字节。因此,当collectgarbage
显示您使用了 19.4775390625KiB 时,这相当于 19945 字节。而您的分配器中可能存在多个值之一。您的内存检查函数只会在
collectgarbage
返回时匹配 Lua 得到的值。在此之前或之后发生的 Lua 分配/释放(例如为了调用print
来显示该值而必要的分配/释放)将导致计数错误。简而言之,您希望获得字节精度,但是使用您的代码是不可能实现的。通常情况下,您不必太担心。