使用自定义的Lua分配器来计算内存使用量,但其结果与collectgarbage('count')不同。

最近我尝试跟踪我们项目中的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

点赞
stackoverflow用户734069
stackoverflow用户734069

根据 Lua 文档所述,collectgarbage('collect') 返回一个以 千字节(kilobytes) 为单位的值,其中 1KB 等于 1024 字节。因此,当 collectgarbage 显示您使用了 19.4775390625KiB 时,这相当于 19945 字节。而您的分配器中可能存在多个值之一。

您的内存检查函数只会在 collectgarbage 返回时匹配 Lua 得到的值。在此之前或之后发生的 Lua 分配/释放(例如为了调用 print 来显示该值而必要的分配/释放)将导致计数错误。

简而言之,您希望获得字节精度,但是使用您的代码是不可能实现的。通常情况下,您不必太担心。

2012-04-16 02:31:54