When writing software, it's frequently important to ensure that some performance constraints are guaranteed. The standard library has most of the tools needed to ensure the timing and resource consumption of the functions we write.
Say we have two functions and we want to know which one is faster:
def function1(): l = [] for i in range(100): l.append(i) return l def function2(): return [i for i in range(100)]
The timeit
module provides a bunch of utilities to time a function or whole script:
>>> import timeit
>>> print(
... timeit.timeit(function1)
... )
10.132873182068579
>>> print(
... timeit.timeit(function2)
... )
5.13165780401323
From the reported timing, we know that function2
is twice as fast as function1
.