Timeit. Which code unit executes faster in a Python program? We answer this question with timeit, a module that benchmarks code fragments.
This module provides a standardized way to perform benchmarks. But usually focusing on higher-level concerns and code quality is a better use of your time.
Example. We must import timeit with the "import timeit" statement. This is required unless you use the command-line syntax. Here we time 2 string-creation expressions.
Command-line. The timeit module can be invoked directly from the command-line. This avoids creating an entire new program file. Timeit returns usec (microseconds) in the output.
Tip You will need to be careful with quotation marks when using the command-line. You may need to escape them, depending on your system.
C:\Users\Sam>C:\Python33\python.exe -m timeit "x = \"y\" * 3"
10000000 loops, best of 3: 0.0273 usec per loop
Multiple statements. With timeit, we can use multiple statements—we separate them with a semicolon. This makes it easier to specify longer code fragments.
Note For longer code fragments, please use the setup argument and call a method. The next example demonstrates.
import timeit
# Use semicolon for multiple statements.
print(timeit.repeat("a = 2; a *= 2", number=100000000))
print(timeit.repeat("a = 1; a *= 4", number=100000000))[7.334341642836696, 7.333336683198793, 7.332224095625474]
[7.235993375046725, 7.247406798908553, 7.256258872415835]
Methods, setup. We can benchmark custom methods in timeit by specifying a setup argument. In this argument, please specify an import statement that indicates the methods you invoke.
Also I found that the ordering of calls to timeit impacts the results. This makes it harder to trust the results of timeit.
A summary. It usually costs more time running micro-benchmarks that you will get back in increased speed. With timeit, we have another benchmarking option.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 29, 2022 (edit link).