Python:timeit
lastmod 2024-08-02created 2024-08-022 edits
Measure execution time of small code snippets
Basic examples
The following example shows how to use the command-line interface to compare three different expressions:
python -m timeit "'-'.join(str(n) for n in range(100))"
## 10000 loops, best of 5: 30.2 usec per loop
python -m timeit "'-'.join([str(n) for n in range(100)])"
## 10000 loops, best of 5: 27.5 usec per loop
python -m timeit "'-'.join(map(str, range(100)))"
## 10000 loops, best of 5: 23.2 usec per loop
With the Python interface, this can be done as follows:
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
## 0.3018611848820001
timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
## 0.2727368790656328
timeit.timeit('"-".join(map(str, range(100)))', number=10000)
## 0.23702679807320237
A callable can also be passed to the Python interface:
Note, however, that timeit() automatically determines the number of repetitions only when the command-line interface is used. More advanced examples can be found in the Examples section.
See also
- Python
- Python:datetime
- Python:time
- Python:timeit - function-level performance measurement.