A424 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

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?

Name it

Counting the work

Instead of timing a program, count its basic steps as a function of the input size n, and keep only the part that grows fastest. That's its order of growth, written with big-O:

OrderExamplen=103n=106
O(1)look up a list item or dictionary key11
O(log⁡n)binary search1020
O(n)sum a list; find the max103106
O(nlog⁡n)sort; FFT1042×107
O(n2)compare all pairs; naive DFT1061012

At roughly 107 simple Python steps per second, 1012 steps is more than a day. Lowering the order beats any amount of tuning.

Reading the order from code:

  • one loop over the data: O(n);
  • a loop inside a loop, both over the data: O(n2);
  • halving the problem each pass: O(log⁡n).

Rewriting to a lower order

The commonest win is to stop redoing work. Computing every running total by re-adding from the start is O(n2):

running = [sum(x[:k + 1]) for k in range(len(x))]     # O(n²)

Carrying the total forward is O(n):

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, O(n); v in a_set is O(1) on average.

Measuring

time.perf_counter() gives a precise clock. Time a function at n and 2n: 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
  1. Count the pairs. 5000×49992=12497500≈1.25×107 comparisons, a second or two in Python.
  2. 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 1.25×107 comparisons for every pair, against 5000 steps with a set.

Worked example

A naive DFT of N samples takes N2 multiplications; an FFT about Nlog2⁡N. Compare them for N=220.

Show the solution
  1. The naive DFT. N2=240≈1.1×1012
  2. The FFT. Nlog2⁡N=220×20≈2.1×107
  3. Compare. The FFT does about 50,000 times less work.
  4. Why it matters. That ratio is why spectrum analyzers, audio codecs and radio receivers all became practical once the FFT was found.

Answer about 1.1×1012 multiplications for the DFT against 2.1×107 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, ⌈log2⁡(N+1)⌉.

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 nlog2⁡n. It takes 2.0 s on 220 items. How long should it take on 222 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 O(n2) to O(n)?

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.