Profiling a slow script
Measure first
A slow script has one or two expensive lines, and guessing which is the first mistake. Start with a benchmark that runs the suspect code twice, once as written and once with the replacement:
require "benchmark" Benchmark.bm(12) do |x| x.report("concat") { out = ""; 50_000.times { out += "x" } } x.report("append") { out = +""; 50_000.times { out << "x" } } end
ruby bench.rb
user system total real
concat 0.530524 0.987800 1.518324 ( 1.520236)
append 0.014788 0.002689 0.017477 ( 0.017502)
The first line allocates a new string and copies the old one on every iteration, so the work grows with the square of the count. The second appends in place. Nearly a hundred times faster is the answer a profile would take an hour to reach. The times themselves move by a few percent from one run to the next; the gap between the two lines is what repeats.
The fix
The fix in the real code is one character. Both programs below build the same report, the first by copying it on every row and the second by appending to it:
rows = [["ada", 3], ["grace", 5]] copied = +"" rows.each { |name, count| copied += format("%-10s %d\n", name, count) } appended = +"" rows.each { |name, count| appended << format("%-10s %d\n", name, count) } print copied print appended puts copied == appended
ruby fix.rb
ada 3
grace 5
ada 3
grace 5
true
<< appends to the same string; += is copied = copied + ... and copies the whole string. The same trap appears with join in a loop instead of one join at the end, and with an array that is converted to a string on every iteration.
Measure again
A fix without a second measurement is a guess with a story. Run the same benchmark on the changed code and compare the real column; a change that moves five percent is noise on this machine, and a change that moves ninety is a result.
The second measurement also catches the fix that moved the cost: a string built once is faster, and a memory profile now shows one large string instead of a hundred thousand small ones. Whether that is better depends on what the report does next.
A flame graph
When the slow code is not obvious, a sampling profiler shows where the time went. stackprof writes a dump and the report groups the samples by frame:
gem install stackprof
1 gem installed
ruby -r stackprof -e 'StackProf.run(mode: :cpu, out: "/tmp/stackprof.dump") { 100_000.times { |i| i.to_s } }'
stackprof /tmp/stackprof.dump --text
The gem builds a native extension, so these three commands ran on the host in the ruby:3.4 image; lesson 7.7 shows the report they print. Read SAMPLES as the time in the frame itself and TOTAL as the time including its calls; the leaf with the largest sample count is the line to change.
A flame graph in a browser is the same data drawn as nested bars. The wide bar at the bottom is the whole program; the wide bar near the top is the function that owns the time.
What to watch for
A micro-benchmark measures the loop and not the program. A method that is
fast in isolation can still dominate a request because it is called a
thousand times; a profiler shows the call count and the total.
Optimise the line the profile names, not the line that looks slow. Sorting
one array of ten items is cheap even when it looks like the expensive
step; the network call before it is usually the answer.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
out += "x"do to a string inside a loop?Answer
It builds a new string and copies the old contents into it on every step
+= is assignment: the right side makes a new string from the old one, so the copying grows with the square of the count.
-
What does this program print?
out = +"" 3.times { |i| out += i.to_s } p out p out.sizeAnswer
"012" / 3
The loop appends the text of each index, and the result is one three-character string.
-
What does this program print?
out = +"" ids = [] 3.times { out += "x"; ids << out.object_id } p ids.uniq.sizeAnswer
3
Every += produces a different string object, so the three object ids are three distinct values.
-
What does this program print?
out = +"" ids = [] 3.times { out << "x"; ids << out.object_id } p ids.uniq.sizeAnswer
1
<< appends to the receiver and returns it, so all three ids belong to the same string object.
-
In a
Benchmark.bmreport, what does therealcolumn measure?Answer
The wall-clock time the block took, including waiting and the scheduler
real is elapsed time; total adds user and system time, which can be larger or smaller than real time.
-
Why can a micro-benchmark point at the wrong line of a real program?
Answer
A method that is fast in isolation can still dominate a request when it runs a thousand times
Only the whole program shows how often a line runs, and a profiler gives both the count and the total time.
-
What does this program print?
a = +"ab" b = a b << "c" p a p b.equal?(a)Answer
"abc" / true
b and a are the same object, and << changes it in place, so both names see the third character.
-
What does a sampling profiler record?
Answer
The call stack at regular intervals while the program runs
It interrupts the program on a timer and stores the stack, so the frames that appear most often own the time.
-
On a flame graph, which bar shows the function that owns the time?
Answer
A wide bar near the top, where a function fills most of its caller
Width is time: a frame that covers most of its parent owns the time of that parent.
-
In a stackprof text report, what is the difference between
SAMPLESandTOTAL?Answer
SAMPLES is the time in the frame itself, TOTAL the time including the calls it made
A frame with few samples of its own and a large total is waiting on its children, so the leaf with the most samples is the place to change.
Article author: Arthur Isaev