Table of Contents
Motivation
Sometimes you want to know how fast your code is. Before you start implementing a timer use the Python built-in timeit module.
#measurewhatmatters
Example
Let’s take a simple function like a recursive implementation of factorial:
def factorial(n):
if n > 0:
return n * factorial(n-1)
else:
return 1
If you want to test how it performs you can now do the following
import timeit
print(f"Self-written recursive: {str(timeit.timeit(lambda: factorial(100)))}")
On my machine the output is
$ python factorial_test.py
Self-written recursive: 9.867481705005048
Note: The amount of time is so high because timeit executes your code 1,000,000 times!
Now you can start to compare your algorithm with others like e.g. the built-in math.factorial
import math
print(f"Built-In: {str(timeit.timeit(lambda: math.factorial(100)))}")
$ python factorial_test.py
Self-written recursive: 9.635978688995237
Built-In: 0.9801331740018213
Now you can see that my own implementation is almost 10x slower than Python’s built-in
Bottom line
The timeit module gives you a neat approach to check for the performance of your code.
Whenever you are developing algorithms you should also check for corresponding built-in functionality because it might be faster.
Complete code
import timeit
import math
def factorial(n):
if n > 0:
return n * factorial(n-1)
else:
return 1
print(f"Self-written recursive: {str(timeit.timeit(lambda: factorial(100)))}")
print(f"Built-In: {str(timeit.timeit(lambda: math.factorial(100)))}")