A4 · Lesson 24 · How running time grows
Twice the data, four times the wait
A script that checks every pair of 100 sensor readings runs in a blink. Give it 100,000 readings and it takes hours. Nothing about the code changed; the amount of data did, and the work grew as the square of it. Knowing how an algorithm's cost grows with its input tells you, before you run anything, whether it'll finish in a second or a week, and which part of a program is worth making faster.
Predict
A function compares every pair of items in a list. With 1000 items it takes 1 second. About how long with 2000?
About 4 seconds. There are pairs, close to , so doubling multiplies the pairs by four. This is quadratic growth, written .
Name it
Counting the work
Instead of timing a program, count its basic steps as a function of the input size , and keep only the part that grows fastest. That's its order of growth, written with big-O:
| Order | Example | ||
|---|---|---|---|
| look up a list item or dictionary key | 1 | 1 | |
| binary search | 10 | 20 | |
| sum a list; find the max | |||
| sort; FFT | |||
| compare all pairs; naive DFT |
At roughly simple Python steps per second, steps is more than a day. Lowering the order beats any amount of tuning.
Reading the order from code:
- one loop over the data: ;
- a loop inside a loop, both over the data: ;
- halving the problem each pass: .
Rewriting to a lower order
The commonest win is to stop redoing work. Computing every running total by re-adding from the start is :
running = [sum(x[:k + 1]) for k in range(len(x))] # O(n²)
Carrying the total forward is :
running, total = [], 0
for v in x:
total += v
running.append(total) # O(n)
Membership tests are another: v in a_list scans the list, ; v in a_set is on average.
Measuring
time.perf_counter() gives a precise clock. Time a function at and : if the time doubles it's linear, if it quadruples, quadratic. Very small runs are dominated by overhead, so measure with inputs large enough to take a noticeable fraction of a second.
Why NumPy is fast
A loop in Python spends most of its time interpreting each step. NumPy runs the same loop in compiled code, often 50 to 100 times faster. It doesn't change the order of growth, but it moves the constant a long way. Lesson 29 is about writing arithmetic so NumPy can do it.
Worked example
How many comparisons does it take to check every pair of 5000 readings for duplicates? And with a set?
Show the solution
- Count the pairs. comparisons, a second or two in Python.
- Use a set instead. Put each reading in a set and check whether it was already there: 5000 steps, about a thousandth of the time.
seen = set()
dupes = []
for v in readings:
if v in seen:
dupes.append(v)
seen.add(v)
Answer about comparisons for every pair, against 5000 steps with a set.
Worked example
A naive DFT of samples takes multiplications; an FFT about . Compare them for .
Show the solution
- The naive DFT.
- The FFT.
- Compare. The FFT does about 50,000 times less work.
- Why it matters. That ratio is why spectrum analyzers, audio codecs and radio receivers all became practical once the FFT was found.
Answer about multiplications for the DFT against for the FFT, about 50,000 times less work.
Check
Write count_pairs(n) that loops over all pairs i < j of n items and counts them. Set c = count_pairs(n) and formula = n * (n - 1) // 2.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Rewrite the running total so it carries the sum forward in one pass. Set running to the list of cumulative sums of x.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Set linear to the number of comparisons a linear search needs in the worst case on N = 1000000 items, and binary to the worst case for binary search, .
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Set dupes to the sorted list of values that appear more than once in x, using a set so the work is linear.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write has_pair(xs, target) that returns True if two different entries of xs add up to target, in one pass with a set of the values seen so far (no nested loops). Then set found for the starter's readings and target = 7.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A sort takes time proportional to . It takes 2.0 s on items. How long should it take on items?
Write units the way you normally would: 1.5 s and 1500 ms are the same answer.
Explain why
Why does halving the time per step matter less than reducing an algorithm from to ?
Halving the time per step makes the program twice as fast at every size, a fixed factor. Going from to divides the work by about , so the gain grows with the input: a thousand times faster at a thousand items and a million times faster at a million. For large inputs the order of growth dominates any constant-factor improvement.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.