8/40
Part 2 of 8 · The heapLearn and do

Count the compares with a class whose __lt__ adds one

Python's < calls an object's __lt__ method, and heapq compares two items with <. So to count compares, use a class whose __lt__ adds one to a counter. On 100,000 random floats:

Way to get thereComparisonsPer item
heapq.heapify165,0001.65
heappush one at a time, random order227,4192.27
heappush one at a time, largest first1,468,94614.69
sorted()1,529,07115.29
heappop all 100,000 from a heap1,534,82315.35

log⁡2100,000\log_2 100{,}000 is about 16.6. In random order most pushes stop near the bottom, so pushing is cheap on average. Largest first is the worst case: every new item is the smallest so far, and it climbs all the way to the root.

Popping everything is a sort, called heapsort, and it costs what a sort costs. On a million random floats, heapifying a copy took 25.7 ms, a million pushes 46.7 ms, and sorted() 137.1 ms.

In the editor, Counted wraps a number, and Counted.compares is one counter that every Counted shares. by_heapify and by_pushes are the two ways to build a heap. Write __lt__ so each < adds one, then count_compares(build, values), which counts the compares one build makes.