Created
July 31, 2021 09:26
-
-
Save Priler/0a8ad354b0e6e5bd910cac86647e56ac to your computer and use it in GitHub Desktop.
Simple performance measure test for Heapq.nlargest vs sort() in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def naive_find_top_k(values, k=20): | |
values.sort(reverse=True) | |
return values[:k] | |
import heapq | |
def heap_find_top_k(values, k=20): | |
return heapq.nlargest(k, values) | |
import random | |
randomlist = [] | |
for i in range(0,10_000_000): | |
n = random.randint(1,30) | |
randomlist.append(n) | |
import time | |
start_time = time.time() | |
print( naive_find_top_k(randomlist) ) | |
print("SORT --- %s sec" % (time.time() - start_time)) | |
start_time = time.time() | |
print( heap_find_top_k(randomlist) ) | |
print("HEAPQ --- %s sec" % (time.time() - start_time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment