Skip to content

Instantly share code, notes, and snippets.

@dzimine
Last active January 31, 2023 04:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzimine/56a90901deb1ef059d822f5fd1fdff21 to your computer and use it in GitHub Desktop.
Save dzimine/56a90901deb1ef059d822f5fd1fdff21 to your computer and use it in GitHub Desktop.
Measure execution time with Python timeit.

Measure execution time with Python timeit module.

Example: compare the sort time between sorting list and sorting dict.

Generate sample dict, sort it:

di = {i:random.randint(1,100) for i in range(0,10)}   
sorted(ls, key=lambda pair: pair[1]) 
[(1, 10),
 (7, 38),
 (9, 43),
 (4, 46),
 (5, 66),
 (3, 71),
 (2, 80),
 (8, 81),
 (6, 86)]

Generate sample list, sort it:

ls = [(x, random.randint(1,100)) for x in range(1,10)]
sorted(di.iteritems(), key=lambda (k,v): (v,k))
[(2, 15),
 (0, 23),
 (6, 24),
 (4, 29),
 (1, 33),
 (8, 35),
 (3, 79),
 (7, 83),
 (9, 85),
 (5, 96)]

Now use timeit to compare the performance:

timeit.timeit('sorted(di.iteritems(), key=lambda (k,v): (v,k))', setup='import random\ndi = {i:random.randint(1,100) for i in range(0,100000)}', number=100)
13.33042287826538

timeit.timeit('sorted(ls, key=lambda pair: pair[1])', setup='import random\nls = [(x, random.randint(1,100)) for x in range(1,100000)]', number=100)
6.257278919219971

The sort complexity is obviously the same, but sorting the list is consistently 2x faster.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment