In [ ]:
import heapq
In [ ]:
%load_ext memory_profiler
In [36]:
# generator of this size
n = 20000000
k = 10
In [41]:
def get_it():
return (-a for a in range(n))
In [18]:
%%time
sorted(get_it(), key=lambda x: x)[:k]
Out[18]:
In [40]:
%%memit
sorted(get_it(), key=lambda x: x)[:k]
In [34]:
%%time
heapq.nsmallest(k, get_it())
Out[34]:
In [39]:
%%memit
heapq.nsmallest(k, get_it())
In [ ]:
def get_it_tuple():
return ((a, -a) for a in range(n))
In [46]:
%%timeit
sorted(get_it_tuple(), key=lambda x: x[1])[:10]
In [47]:
%%memit
sorted(get_it_tuple(), key=lambda x: x[1])[:10]
In [43]:
%%timeit
heapq.nsmallest(k, get_it_tuple(), key=lambda x: x[1])
In [44]:
%%memit
heapq.nsmallest(k, get_it_tuple(), key=lambda x: x[1])