lua-users home
lua-l archive

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


On Thu, 7 Feb 2002, Max Ischenko wrote:

> Is there a known way to profile Lua code?


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 = tostring(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 ()
    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.)

-- Roberto