How to reduce benchmark overhead
masterWhen benchmarking extremely small workloads, the overhead of the benchmark loop itself can introduce errors. There are two ways to mitigate this:
- Manual Iteration Loop: Pass a block that accepts a
timesargument. You must run your code exactlytimestimes inside a loop. This is the recommended approach for reducing overhead. - Code Grafting: Pass the code as a string as the second argument to
x.report. This grafts the code directly into the internal loop. This is typically not needed if you use the|times|form.
# Method 1: Manual loop (Recommended)
x.report("addition2") do |times|
i = 0
while i < times
i += 1
1 + 2
end
end
# Method 2: Code grafting
x.report("addition3", "1 + 2")