Profiling Lua Code

lua-users home
wiki

Lua Profilers

These profilers have been provided for Lua:

You can also write your own through the Lua Debug library [1].

See also OptimisationTips.

Older Lua 4 Example

[!] VersionNotice: The below code pertains to an older Lua version, Lua 4. It does not run as is under Lua 5.

Here are some methods for profiling Lua code (from Roberto) :-

A very naive way:

setcallhook(function (event)
  local x = getinfo(2, 'nS')
  print(event, x.name, x.linedefined, x.source, clock())
end) 

A first improvement is to recode it in C. A second (but major) improvement is to do most computations inside the program to reduce output (see Another way).

Despite its naivity, it works. I use it frequently. Of course the clock is not very accurate, the hook itself affects all times, and the result can be huge. But is still can give you a rough idea of what is going on inside your code.

Another way:

local T = {}
setcallhook (function (event)
  local f = getinfo(2, 'f').func
  local e = %T[f]
  if e == nil then
    local x = getinfo(2, 'nS')
    e = {name = x.name, line = x.linedefined, source = x.source,
                 time = 0, count = 0}
    %T[f] = e
  end
  if event == 'call' then
    e.time = e.time - clock()
    e.count = e.count + 1
  else
    e.time = e.time + clock()
  end
end)

-- You must call `dump' when your program ends
function dump ()
  setcallhook()   -- cannot change `T' during traversal!
  for k,v in %T do
    print(v.name, v.line, v.source, v.count, v.time)
  end
end 

(Again, that in C affects much less your program.)


RecentChanges · preferences
edit · history
Last edited May 8, 2013 5:45 pm GMT (diff)