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.