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 there | Comparisons | Per item |
|---|---|---|
heapq.heapify | 165,000 | 1.65 |
heappush one at a time, random order | 227,419 | 2.27 |
heappush one at a time, largest first | 1,468,946 | 14.69 |
sorted() | 1,529,071 | 15.29 |
heappop all 100,000 from a heap | 1,534,823 | 15.35 |
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.