In most programming scenarios, it is very easy to re-invent the wheel especially when you are working with high-level languages like Python. For example, in a scenario where you want to measure the execution time of a block of code like a function, you might hastily turn to time.time() or other similar functions. But there is a module that is designed specifically for this purpose, it is called timeit.
The timeit module defines some useful function for measuring the execution time of small code snippets. It makes it easy to benchmark small blocks of code , making it even easier to optimize performance by comparing different implementations.
Unlike other manual approaches, timeit automatically handles multiple repetitions and platform-independent timing.
timeit is a standard library module and you don't need to perform any extra installations, you just need to import it in your code.
Basic usage of timeit
For basic usage, you will use the following timeit functions:
timeit.timeit()timeit.repeat()
using timeit.timeit()
The timeit.timeit() function runs a given statement multiple times and returns the total execution time.
The basic syntax is as shown below:
timeit.timeit(stmt, number)
Where:
stmtis the statement/code to be timed, it is either a callable(usually a function) or a string.numberis how many times to repeat the statement, it defaults to1000,000times.
Using timeit.repeat()
This function repeats the timing process multiple times and returns a list of results.
The basic syntax is as follows:
timeit.repeat(stmt, number, repeat)
Where repeat is the number of repetitions, it defaults to 5 times
Technically, the timeit.repeat() function runs the code using timeit.timeit() the specified number of times and appends the results in a list.
timeit with string statements
In the previous examples, we called timeit functions with a callable/function argument. It is also possible to pass a code snippet as a string.
setup code
You can add setup code to contextualize the execution by specifying the setup parameter.
Running timeit from the Command Line
You can use timeit in terminals too. You will simply pass your code as a command-line argument:
python -m timeit "[i for i in range(100)]"
You can specify the parameters as follows:
-n, number-r, repeats
python -m timeit -n 1000 -r 3 "[i for i in range(100)]"
Class based timing
Class-based timing with timeit.Timer offers even more control. You can persist setup between runs or change parameters dynamically.
The Timer class constructor takes the same basic parameters as the timeit.timeit() function.
The created timer object has three key methods:
timeit(number=1000000)- Single timing run.-
repeat(repeat=5, number=1000000)- Multiple timing runs -
autorange()- Automatically determine optimal iterations
Let us wrap up by implementing a more practical example of comparing the performance of three sorting approaches, i.e sorted(x), x.sort() and Heap sort.