lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Hi list,

for some benchmarking purposes I patched the default allocator
function in Lua to track the memory usage during the execution of a
script. I'm posting that patch to the list in case it is useful for
somebody else as well.

diff -urN lua-5.1.2/src/lauxlib.c lua-5.1.2_alloctrace/src/lauxlib.c
--- lua-5.1.2/src/lauxlib.c     2006-03-21 20:31:09.000000000 +0100
+++ lua-5.1.2_alloctrace/src/lauxlib.c  2007-07-12 16:55:17.000000000 +0200
@@ -627,13 +627,27 @@

static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
-  (void)osize;
  if (nsize == 0) {
+    if (ptr)
+      fprintf(stderr, "lua free %u\n", osize);
    return NULL;
+  {
+    if (osize)
+    {
+      if (osize < nsize)
+        fprintf(stderr, "lua alloc %u\n", nsize - osize);
+      else
+        fprintf(stderr, "lua free %u\n", osize - nsize);
+    }
+    else
+      fprintf(stderr, "lua alloc %u\n", nsize);
    return realloc(ptr, nsize);
+  }

How it works: per allocation and free it prints a line to stderr with
the amount of bytes being requested/freed. If you redirect stderr to a
file you can unleash the following Lua script on it to transform the
data in a list of total amount of allocated memory at each
allocation/free. If you redirect the output of that script to another
file you can then plot those numbers in a nice graph.

-- begin memusage.lua
local memusage = 0
for line in io.lines(arg[1]) do
 local amount = string.match(line, "alloc (%d+)")
 if amount then
   memusage = memusage + amount
   amount = string.match(line, "free (%d+)")
   if amount then
     memusage = memusage - amount
-- end memusage.lua