A collection of scripts to demonstrate very easy ways to benchmark code or time execution. These scripts are presented as a starting off point to get you thinking about performance and measurement.
One of the example files requires a dependency that can be loaded using pip. To install the dependencies from the included requirements file use the -r
flag as shown in the example below.
$ pip install -r requirements.txt
This example demonstrates the use of the time
utility as found on most Unix like personal computers (may not be available on Windows). For more information on how to use the command, consult the man file with man time
.
For a quick explanation of real, user, and sys values please review this Stack Overflow answer.
Usage:
$ time python 1-example.py 10000
This example script provides the most straightforward method to provide the elapsed time for a piece of code.
Usage:
$ python 2-example.py 10000
This example script uses a slightly more sophisticated method for timing a block of code through the use of Python context managers. For more information on context managers and the "with" statement consult PEP 343.
Usage:
$ python 3-example.py 10000
Finally, our last example uses the line_profiler library to provide line by line statistics into code execution and performance. For more information, visit the Github repository page at https://github.com/rkern/line_profiler.
Notice how much time this level of profiling adds to the overall execution.
Usage:
$ kernprof -l -v 4-example.py 10000