🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Profiling with Counters

Profiling with counters measures how much work code does. A counter is a variable that grows by one each time a chosen action runs.

Count instructions with a hook

Turn the hook on, run a small loop, then turn the hook off. The printed count covers that loop, including the hook machinery.

local count = 0
debug.sethook(function() count = count + 1 end, "", 1)
local total = 0
for i = 1, 3 do total = total + i end
debug.sethook()
print(count)
print(total)

Compare versions with the same shape

Both versions run the same kind of loop, so the comparison is fair. More work gives a larger count.

local function run(n)
  local count = 0
  debug.sethook(function() count = count + 1 end, "", 1)
  local total = 0
  for i = 1, n do total = total + i end
  debug.sethook()
  return count, total
end
local c3, t3 = run(3)
local c6, t6 = run(6)
print(c3, t3)
print(c6, t6)
print(c6 > c3)

Prefer a counter the code maintains

This counter grows once per loop pass. It needs no hook at all.

local steps = 0
local total = 0
for i = 1, 4 do
  steps = steps + 1
  total = total + i
end
print(steps)
print(total)

Example

local hookCount = 0
debug.sethook(function() hookCount = hookCount + 1 end, "", 1)
local total = 0
local steps = 0
for i = 1, 5 do
  total = total + i
  steps = steps + 1
end
debug.sethook()
print(hookCount)
print(steps)
print(total)

Key points

  • Counter: a variable that grows by one for each action it counts.
  • Hook: a function Lua calls at set points while a program runs.
  • Count hook: a hook that fires after a set number of instructions.
  • Use a count hook to count instructions between turning the hook on and turning it off.
  • Compare only versions with the same shape, because hook counts include hook machinery.

In this example, a count hook counts instructions while a loop adds numbers and a self-maintained counter counts passes. The hook is turned off before printing. The prints show the hook count, the pass count, and the total.

Note

a counter the code itself maintains is the simplest proof when a plain count answers the question.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A count hook reports 14 for one loop and 20 for a longer loop of the same shape. What is the safe conclusion?