7/41
Part 1 of 7 · SortingLearn

On a million floats a sort costs about 25 passes over them, so sort once

In time, on random floats:

nsorted(d)Per itemsorted of already sorted datamin(d), one pass
10,0000.84 ms84 ns0.04 ms0.06 ms
100,00011.24 ms112 ns0.44 ms0.62 ms
1,000,000152.23 ms152 ns21.30 ms5.96 ms

Python 3.12, best of 5 runs with timeit, on the laptop these numbers come from.

The time per item grows with n, roughly as the log⁡n\log n in the cost predicts. The comparison counts from the step on what a sort costs are the cleaner evidence.

The jump for sorted data at a million is memory, not comparisons. In a separate run, just copying the list went from 0.21 ms at 100,000 items to 8.13 ms at a million.

A sort is 25 times one pass over a million items. So sort once and reuse the order. Never sort inside a loop.

Memory, measured with tracemalloc on a million floats: sorted(d) peaked at 11.44 MiB. That's 8 MB for the new list of pointers, plus scratch space for merging runs. d.sort() peaked at 3.81 MiB, the scratch space alone.