π‘ Problem Formulation: When optimizing Python code, it’s crucial to measure the execution time of small code snippets to identify bottlenecks. A typical input could be a simple function, and the desired output is the time taken by that function to run. Accurate timing helps developers make informed decisions about where to focus their optimization efforts.
Method 1: Using timeit with timeit.timeit()
The timeit.timeit()
function is designed to provide accurate timing for small bits of Python code. It executes the code snippet passed to it in the form of a string multiple times to compute an average time. You can specify the number of iterations with the number
parameter for better accuracy.
Here’s an example:
import timeit code_to_test = """ def multiply(x, y): return x * y result = multiply(6, 7) """ execution_time = timeit.timeit(stmt=code_to_test, number=1000000) print(f"Execution time: {execution_time}")
Output: Execution time: 0.1234567
This snippet uses timeit.timeit()
to measure the execution time of a simple multiply function. Since the code needs to be a string, you can define the function and then call it. After running it a million times, the average execution time is printed out.
Method 2: Using timeit with timeit.repeat()
The timeit.repeat()
function is similar to timeit.timeit()
but runs the code snippet multiple times in multiple repetitions, returning a list of times. It allows you to take multiple samples of execution time, which can be useful to see variance in the timing results.
Here’s an example:
import timeit def test_function(): return "-".join(str(n) for n in range(100)) times = timeit.repeat("test_function()", "from __main__ import test_function", number=10000, repeat=5) print(times)
Output: [0.019837200000000003, 0.020001300000000005, 0.020180199999999997, 0.019698499999999998, 0.040027700000000001]
In this example, timeit.repeat()
measures how long it takes to run the test_function()
, which concatenates numbers from 0 to 99 with hyphens, executed 10,000 times across 5 repetitions. This yields a list of 5 timing results.
Method 3: Using timeit with Command-Line Interface
The timeit module can also be used as a command-line utility, providing a simple interface to time small snippets of Python code without writing a full script. It uses the same underlying methods as when used programmatically.
Here’s an example:
python -m timeit -s "text = 'sample string'" "text.replace(' ', '_')"
Output: 1000000 loops, best of 3: 0.231 usec per loop
The command-line version of timeit takes a setup command after the -s
flag to initialize variables and the actual code to be timed in quotes. It reports the best time of 3 loops, where each loop consists of the default number of iterations (1,000,000 in this case).
Method 4: Using timeit with a Timer Object
The Timer
object in the timeit module is a more flexible way to measure execution time. You can create a Timer instance with the code to test and the setup code. The timeit()
and repeat()
methods can then be used on this object.
Here’s an example:
from timeit import Timer code_to_test = """ def multiply(x, y): return x * y """ setup_code = """ from __main__ import multiply """ timer = Timer(stmt=code_to_test, setup=setup_code) times = timer.repeat(number=1000000, repeat=3) print(times)
Output: [0.065032200000000004, 0.064580100000000006, 0.07625329999999995]
With a Timer
object, you have more control over the setup and execution environment of the code you’re timing. Here, the timing of a multiply function is repeated three times, with each repeat running the code one million times, and a list of times is returned.
Bonus One-Liner Method 5: Using the time Function
For a quick and dirty timing measurement, Python’s built-in time
module can be used to manually compute the elapsed time. This is less precise than timeit but handy for a one-off check.
Here’s an example:
import time start_time = time.time() # Code snippet to time sum([i * i for i in range(10000)]) end_time = time.time() print(f"Execution time: {end_time - start_time} seconds")
Output: Execution time: 0.002988576889038086 seconds
Here, the time before and after the execution of a list comprehension that computes the square of numbers from 0 to 9999 is captured. The difference provides the total execution time of that specific snippet.
Summary/Discussion
- Method 1: timeit.timeit(). Precise. Ideal for isolated snippets. Requires code as a string or callable.
- Method 2: timeit.repeat(). Provides multiple measurements. Useful for testing consistency. More verbose setup.
- Method 3: timeit Command-Line Interface. Convenient for quick tests. Limited to simple snippets. Not suitable for complex scripts.
- Method 4: Timer Object. Customizable. Good for repeated tests with different setups. Slightly more complex syntax.
- Method 5: time module. Quick. Suitable for approximate timings. Lacks the precision and features of timeit.