---
title: How running time grows
heading: Twice the data, four times the wait
eyebrow: A4 · Lesson 24 · How running time grows
xp: 40
---

::: hook
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?

- [ ] 1 second
- [ ] 2 seconds
- [x] 4 seconds
- [ ] 1000 seconds

::: reveal
About 4 seconds. There are $n(n - 1)/2$ pairs, close to $n^2/2$, so doubling $n$ multiplies the pairs by four. This is **quadratic** growth, written $O(n^2)$.
:::
:::

::: nameit
## 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:

| Order | Example | $n = 10^3$ | $n = 10^6$ |
|---|---|---|---|
| $O(1)$ | look up a list item or dictionary key | 1 | 1 |
| $O(\log n)$ | binary search | 10 | 20 |
| $O(n)$ | sum a list; find the max | $10^3$ | $10^6$ |
| $O(n \log n)$ | sort; FFT | $10^4$ | $2 \times 10^7$ |
| $O(n^2)$ | compare all pairs; naive DFT | $10^6$ | $10^{12}$ |

At roughly $10^7$ simple Python steps per second, $10^{12}$ 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(n^2)$;
- 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(n^2)$:

```
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.
:::

::: example
## How many comparisons does it take to check every pair of 5000 readings for duplicates? And with a set?

::: solution
1. **Count the pairs.**
   $$\begin{aligned} \frac{5000 \times 4999}{2} &= 12\,497\,500 \\ &\approx 1.25 \times 10^7 \end{aligned}$$
   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 \times 10^7$ comparisons for every pair, against 5000 steps with a set.
:::
:::

::: example
## A naive DFT of $N$ samples takes $N^2$ multiplications; an FFT about $N\log_2 N$. Compare them for $N = 2^{20}$.

::: solution
1. **The naive DFT.**
   $$\begin{aligned} N^2 &= 2^{40} \\ &\approx 1.1 \times 10^{12} \end{aligned}$$
2. **The FFT.**
   $$\begin{aligned} N\log_2 N &= 2^{20} \times 20 \\ &\approx 2.1 \times 10^7 \end{aligned}$$
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 \times 10^{12}$ multiplications for the DFT against $2.1 \times 10^7$ for the FFT, about 50,000 times less work.
:::
:::

::: check
kind: python
given: n = 10..200 int

## 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 starter
def count_pairs(n):
    return n

c = count_pairs(n)
formula = 0
print(c, formula)
```

```python solution
def count_pairs(n):
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            count += 1
    return count

c = count_pairs(n)
formula = n * (n - 1) // 2
print(c, formula)
```

```python tests
assert count_pairs(4) == 6, "4 items make 6 pairs: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). Loop j from i + 1."
assert c == formula == n * (n - 1) // 2, "c and formula should both be n(n − 1)/2."
```

::: right
Right. The loop inside a loop is where the $n^2$ comes from.
:::
:::

::: check
kind: python
given: k = 0..3 int

## Rewrite the running total so it carries the sum forward in one pass. Set `running` to the list of cumulative sums of `x`.

```python starter
x = [[3, 1, 4, 1, 5, 9, 2, 6], [10, -2, 7, 0, 3], [1] * 12, [2.5, 0.5, -1.0, 4.0]][k]
running = [sum(x[:i + 1]) for i in range(len(x))]   # quadratic: rewrite in one pass
running = []
print(running)
```

```python solution
x = [[3, 1, 4, 1, 5, 9, 2, 6], [10, -2, 7, 0, 3], [1] * 12, [2.5, 0.5, -1.0, 4.0]][k]
running, total = [], 0
for v in x:
    total += v
    running.append(total)
print(running)
```

```python tests
xs = [[3, 1, 4, 1, 5, 9, 2, 6], [10, -2, 7, 0, 3], [1] * 12, [2.5, 0.5, -1.0, 4.0]][k]
want = [sum(xs[:i + 1]) for i in range(len(xs))]
assert len(running) == len(want) and all(abs(a - b) < 1e-12 for a, b in zip(running, want)), "running should hold the cumulative sums. Keep a total and append it after each item."
```

::: right
Right. Each step adds one number to the total so far: $n$ additions instead of about $n^2/2$.
:::
:::

::: check
kind: python
given: N = 1000 | 1000000 | 1000000000

## Set `linear` to the number of comparisons a linear search needs in the worst case on `N` = {N} items, and `binary` to the worst case for binary search, $\lceil \log_2(N + 1) \rceil$.

```python starter
import math
linear = binary = 0
print(linear, binary)
```

```python solution
import math
linear = N
binary = math.ceil(math.log2(N + 1))
print(linear, binary)
```

```python tests
import math
assert linear == N, "A linear search may have to look at every item."
assert binary == math.ceil(math.log2(N + 1)), "binary should be ceil(log2(N + 1))."
```

::: right
Right. At a billion items it's a billion comparisons against thirty.
:::
:::

::: check
kind: python
given: k = 0..2 int

## Set `dupes` to the sorted list of values that appear more than once in `x`, using a set so the work is linear.

```python starter
x = [[5, 3, 9, 3, 1, 5, 7], [2, 4, 6, 8, 4], [1, 1, 1, 2, 2, 3]][k]
dupes = []
print(dupes)
```

```python solution
x = [[5, 3, 9, 3, 1, 5, 7], [2, 4, 6, 8, 4], [1, 1, 1, 2, 2, 3]][k]
seen, d = set(), set()
for v in x:
    if v in seen:
        d.add(v)
    seen.add(v)
dupes = sorted(d)
print(dupes)
```

```python tests
xs = [[5, 3, 9, 3, 1, 5, 7], [2, 4, 6, 8, 4], [1, 1, 1, 2, 2, 3]][k]
want = sorted({v for v in xs if xs.count(v) > 1})
assert dupes == want, f"dupes should be {want}: each repeated value once, sorted."
```

::: right
Right. Checking membership in a set takes the same time however big it gets.
:::
:::

::: check
kind: python
given: k = 1..5 int; target = 7 | 10 | 12

## 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` = {target}.

```python starter
import random
random.seed(k)
xs = [random.randint(0, 9) for _ in range(8)]

def has_pair(xs, target):
    for i in range(len(xs)):
        for j in range(len(xs)):
            if xs[i] + xs[j] == target:
                return True
    return False

found = has_pair(xs, target)
print(xs, found)
```

```python solution
import random
random.seed(k)
xs = [random.randint(0, 9) for _ in range(8)]

def has_pair(xs, target):
    seen = set()
    for x in xs:
        if target - x in seen:
            return True
        seen.add(x)
    return False

found = has_pair(xs, target)
print(xs, found)
```

```python tests
import random
random.seed(k)
ys = [random.randint(0, 9) for _ in range(8)]
want = any(ys[i] + ys[j] == target for i in range(len(ys)) for j in range(i + 1, len(ys)))
assert found == want, f"For {ys} and {target} the answer is {want}."
assert has_pair([5], 10) is False, "A single 5 can't pair with itself to make 10: only entries seen before count."
assert has_pair([5, 5], 10) is True and has_pair([1, 2, 3], 7) is False, "Check [5, 5] with 10 (True) and [1, 2, 3] with 7 (False)."
```

::: right
Right. For each value you ask whether its partner, `target - x`, has already gone by, which a set answers in one step. That's linear time where the double loop is quadratic, and it can't pair an entry with itself.
:::
:::

::: check
given: p = 21 | 22 | 24
answer: 2*2^(p-20)*p/20
unit: s
tolerance: 1%

## A sort takes time proportional to $n\log_2 n$. It takes 2.0 s on $2^{20}$ items. How long should it take on $2^{\given{p}}$ items?

::: right
Right. The ratio is $\frac{2^{\given{p}} \cdot \given{p}}{2^{20} \cdot 20}$, a little more than the ratio of the sizes because $\log_2 n$ grows too: {answer}.
:::

::: misses
- [2*2^(p-20)] That scales with $n$ alone. The $\log_2 n$ factor grows too, from 20 to {p}.
- [2*4^(p-20)] That's how an $n^2$ algorithm would scale.
- [2*p/20] That scales only the logarithm. The number of items grew too.
- [any] Not yet. Take the ratio of $n\log_2 n$ at the two sizes and multiply 2.0 s by it.
:::
:::

::: explain
## Why does halving the time per step matter less than reducing an algorithm from $O(n^2)$ to $O(n)$?

::: model
Halving the time per step makes the program twice as fast at every size, a fixed factor. Going from $O(n^2)$ to $O(n)$ divides the work by about $n$, 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

::: check
kind: python
given: n = 1000 | 4000; m = 2 | 3 | 10

## A quadratic algorithm takes 1 s at `n` = {n}. Set `t` to the seconds it takes at `m` = {m} times that size.

```python starter
t = 0
print(t)
```

```python solution
t = m**2
print(t)
```

```python tests
assert t == m**2, "Time grows as the square of the size: m times the size takes m² as long."
```
:::

::: check
kind: python
given: N = 1024 | 65536 | 1048576

## Set `ratio` to how many times fewer multiplications an FFT ($N \log_2 N$) needs than a naive DFT ($N^2$) for `N` = {N}.

```python starter
import math
ratio = 0
print(ratio)
```

```python solution
import math
ratio = N**2 / (N * math.log2(N))
print(ratio)
```

```python tests
import math
assert abs(ratio - N / math.log2(N)) < 1e-9 * N, "ratio should be N² / (N log₂ N) = N / log₂ N."
```
:::
:::
