Julia Profiling Method
A profiling method is a planned way to find where a program spends its effort. The Profile tool stays in words only here, and counts from @allocated give the hard evidence.
Warm up before measuring
A tiny addition needs no new storage after warm-up.
function add_one(x)
return x + 1
end
add_one(3)
println(add_one(41))
println(@allocated add_one(41))A flat read stays flat
Reading one entry needs no new storage. The count stays the same for a small list and a large list.
function first_value(xs)
return xs[1]
end
small = [7, 8, 9]
large = collect(1:1000)
first_value(small)
first_value(large)
println(first_value(small))
println(first_value(large))
println(@allocated first_value(small))
println(@allocated first_value(large))A growing build grows its count
Building a list needs new storage. The count grows as the input grows.
function build_upto(n)
return collect(1:n)
end
build_upto(3)
println(@allocated build_upto(10))
println(@allocated build_upto(100))
println(length(build_upto(100)))Example
function first_value(xs)
return xs[1]
end
function build_upto(n)
return collect(1:n)
end
small = [5, 6, 7]
large = collect(1:1000)
first_value(small)
first_value(large)
build_upto(3)
println(@allocated first_value(small))
println(@allocated first_value(large))
println(@allocated build_upto(10))
println(@allocated build_upto(100))Key points
- Profile: the Profile tool shows where a program spends its effort, and this lesson keeps it in words only.
- Warm-up: run a function once before measuring it, so later counts leave out compilation.
- Counts: @allocated counts bytes a call creates, and it is measured after warm-up in the same block.
- Flat: a function that only reads one entry keeps the same small count for a small input and a large input.
- Growing: a function that builds a new list grows its count as its input grows.
In this example, reading one entry is measured for a small list and a large list. Building a list is measured for 10 entries and 100 entries. The flat counts stay at 0 while the building counts grow from 144 to 928.
Note
never judge speed from one single count, compare counts across input sizes.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What is the first step of the profiling method in this lesson?