I found this to be consistently faster (about 2x for a list of 1,000,000 items) than heapq.nlargest
:
def two_largest(sequence): first = second = 0 for item in sequence: if item > second: if item > first: first, second = item, first else: second = item return first, second
(function modified at the suggestion of MatthieuW)
Here are the results of my testing ( timeit
executed forever, so I used time.time()
):
>>> from random import shuffle >>> from time import time >>> seq = range(1000000) >>> shuffle(seq) >>> def time_it(func, *args, **kwargs): ... t0 = time() ... func(*args, **kwargs) ... return time() - t0 ... >>>
source share