Performance & Profiling
Making code fast is mostly finding out where it is slow: measure, read the profile, fix the one thing that matters, measure again. You count the work instead of guessing at it, from accidental quadratics and caches to memory, waiting on I/O and a latency budget.
- Intermediate
- 4 units, 12 lessons, 150 exercises
- Your language, profiles as text
- Builds on Algorithm Foundations
Unit 01 · 3 lessons
Measure first
Find where the time really goes before you change anything
- 01Timing
Noise, warm-up, the median, and benchmarks that lie
- 02Reading a profile
Self time, total time, call counts and flame graphs
- BOSSFind the bottleneck
Amdahl's law on a slow nightly job, from profile to fix
Read the unit guide
Intuition about speed is usually wrong. Programmers guess the slow part of a program correctly far less often than they think, so the first rule of performance work is to measure before touching anything.
A stopwatch is noisy. The same code on the same input gives a different time on every run: the first run is slow because nothing is warmed up, and other programs steal the CPU now and then. So run it several times, ignore the warm-up, and report the median, which shrugs off the odd bad run. Wall-clock time is what the user waits; CPU time is how long the processor actually computed. A big gap between them means the program was waiting, not working.
A benchmark compares whatever differs between two runs. Make sure the only difference is the thing you care about: same input, same machine, set-up outside the timed part, and inputs that look like real ones instead of the best case.
A profiler tells you where the time goes. Total time is a function plus everything it calls; self time is the function's own lines. Start with the largest self time, and read the call counts: a cheap function called two million times is a question about its caller.
Amdahl's law says what a fix is worth: new time = the part you did not touch + the part you sped up ÷ its speed-up. Making 10% of a run ten times faster saves 9%. Making 80% of it four times faster saves 60%.
The loop is always the same: measure, profile, guess, change one thing, measure again. The bottleneck moves after every fix, so the old profile is out of date the moment the fix lands. Stop when it is fast enough for its job.
Unit 02 · 3 lessons
Do less work
Remove work the program never needed to do
- 01Accidental quadratics
Spot the loop hiding inside an innocent line
- 02Caching
Remember answers, and know when not to
- BOSSA hot loop
Hoist, look up, batch: one slow loop made fast, step by step
Read the unit guide
The fastest code is the code that does not run. Most CPU-bound slowness is not slow instructions: it is the same work done far more often than necessary.
The usual culprit is an accidental quadratic: a loop whose body hides a second loop. A membership test on a list, a search by value, a count, a copy of everything built so far. Each reads like one step and costs up to n. Ask of every line inside a loop: does this take the same time when the data is ten times bigger? The cure is nearly always a set or a dictionary built once, which answers in about one step.
A cache stores answers under a key so the work is done once. It only makes sense when keys repeat: the average cost is hit rate × hit cost + miss rate × miss cost, and the misses dominate. The key must contain everything the answer depends on. Caches need a size limit (evict the least recently used entry) and a plan for answers that stop being true (expire them, or remove them when the source changes).
Inside a hot loop, look for work that does not depend on the loop variable. A total, an average, a set built from another list, a setting read from a file: compute it once above the loop. This is called hoisting.
Fixed overheads are paid per call, so batch: one request carrying 100 rows instead of 100 requests carrying one each.
Count before and after. A change that turns a million steps into two thousand is real on any machine. A change that folds two passes into one is a constant factor, and only a measurement can say whether it helped.
Unit 03 · 3 lessons
Memory
Use less memory, keep it from leaking, and lay data out so it is fast to read
- 01Allocation
What values cost, and streaming instead of building lists
- 02Leaks
Memory that is no longer needed but can still be reached
- BOSSWhere the data sits
Cache-friendly order, and a file larger than memory
Read the unit guide
Space is time, eventually. Every value a program creates has to be allocated, and in a garbage-collected language something later has to work out that it is dead and free it. A program that allocates less has less of both to do.
The cheapest trick is not to hold everything at once. A list of ten million results needs room for ten million results; a stream (a generator or iterator) hands them over one at a time, and a running total needs room for one number. If each item can be handled and forgotten, memory stays flat however large the input is. A stream can be read once, and a step that needs everything, like a sort, ends the streaming.
With a garbage collector, a leak is memory the program no longer needs but can still reach. The collector frees only what nothing refers to. The usual suspects are a cache that only grows, listeners that are never removed, a global list that collects results, and a closure that captures something large.
On a memory graph, a healthy process is a sawtooth: up, then back down to the same floor after each collection. A leak is a floor that keeps rising. To find one, take a heap snapshot, repeat the suspect action many times, take another, and see which kind of object grew and what still refers to it.
Where data sits matters too. The CPU fetches memory in blocks and keeps recent blocks in a cache, so reading neighbours is nearly free and jumping around is not. A contiguous array walked in order beats scattered objects, and row-by-row beats column-by-column on a grid stored by rows, with the same Big-O.
When the data is larger than memory, process it in pieces: one line or one chunk at a time, keeping only the running answer.
Unit 04 · 3 lessons
Waiting
Cut the time a program spends waiting on disks, databases and networks, and hold a page to a latency budget
- 01Waiting on I/O
Count the trips, batch them, and overlap the waits
- 02Latency and the tail
Percentiles, timeouts and what happens when requests queue
- BOSSThe 200 ms page
Trace a slow page, fix what overspends, and guard the budget
Read the unit guide
Most slow programs are not computing. They are waiting: for a disk, a database, another service. The gaps are enormous. If a read from memory counts as 1, a read from a fast disk is roughly 1,000 and a round trip to a far-away server roughly 1,000,000. One avoidable request can outweigh every clever loop in the program.
So for I/O the first thing to count is trips. The classic waste is one query for a list and then one more query per item: 2,000 orders become 2,001 round trips. Fetching all the items in one batched query turns that into 2. Sending rows in batches and caching what is asked for again and again are the same idea.
The second lever is overlap. Waits that do not depend on each other can run at the same time, and then the total is the longest of them, not the sum. Overlap shortens the wait and does not reduce the work: the servers still answer every call. How to start work concurrently is the subject of the concurrency roadmap; here you only need the arithmetic.
Latency is a distribution, and the mean hides it. Sort the times: p50 is the middle one, the typical request, and p99 is the one that 99 in 100 beat. The slow end is called the tail. Tails matter more than they look, because a page that needs many calls is as slow as its slowest call, and with 100 calls a 1-in-100 event happens on most pages. A timeout keeps one stuck call from holding everything up.
A performance budget turns all of this into a number agreed in advance: this page, 200 ms. Trace a request stage by stage, fix the stage that overspends, measure again, and stop when you are inside the budget. Then guard it with a check that cannot flake: count queries, do not time them.
Learn Performance & Profiling on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.