Skip to content

Compare sorting speeds

Choosing a sort · Article 7 of 8 · 3 min read

Measure the algorithms you wrote instead of trusting the theory.

The short version

Timing the same input across algorithms shows how n squared and n log n diverge as the list grows.

Details

Use time.perf_counter() for short timings. Build the input once, copy it for each run, and test more than one size so the trend is visible.

Try it yourself

Reuse insertion_sort and merge_sort from earlier articles.

import random, time

for size in (1000, 4000):
    data = [random.random() for _ in range(size)]
    for name, fn in (("insertion", insertion_sort), ("merge", merge_sort), ("python", sorted)):
        copy = list(data)
        start = time.perf_counter()
        fn(copy)
        print(size, name, round(time.perf_counter() - start, 4))

Quadrupling the size should make insertion sort roughly sixteen times slower and merge sort a little over four times slower.

Explain it to the duck

Why does the built in sort still beat your merge sort at the same size?

Tested with: Python 3.13.