Code
import timeit
def example_function():
return sum(range(1000))
# Measure execution time
execution_time = timeit.timeit(example_function, number=1000)
print(f"Execution time: {execution_time:.6f} seconds")Execution time: 0.057977 seconds
timeit and Bash’s timeMeasuring the execution time of code is essential for performance optimization and debugging. In this article, we’ll explore two tools for timing code: Python’s timeit module and Bash’s time command. These tools help developers understand how long their code takes to execute, enabling better decision-making for optimizations.
timeit ModuleThe timeit module in Python provides a simple way to measure the execution time of small code snippets. It’s particularly useful for benchmarking small pieces of code with high precision.
Here’s how to use timeit to measure the execution time of a Python function:
import timeit
def example_function():
return sum(range(1000))
# Measure execution time
execution_time = timeit.timeit(example_function, number=1000)
print(f"Execution time: {execution_time:.6f} seconds")Execution time: 0.057977 seconds
timeit uses the most accurate timer available on your system.For asynchronous code, timeit can be combined with asyncio to measure execution time. Here’s an example:
import asyncio
import timeit
async def async_example():
await asyncio.sleep(1)
async def measure_time():
start_time = timeit.default_timer()
await async_example()
elapsed_time = timeit.default_timer() - start_time
print(f"Execution time: {elapsed_time:.6f} seconds")
# Check if an event loop is already running
try:
loop = asyncio.get_running_loop()
except RuntimeError: # No event loop is running
loop = None
if loop:
# If an event loop is running, schedule the coroutine
loop.create_task(measure_time())
else:
# If no event loop is running, use asyncio.run()
asyncio.run(measure_time())time CommandThe time command in Bash is a versatile tool for measuring the execution time of commands or scripts. It provides real, user, and system time metrics.
To measure the execution time of a command, simply prefix it with time:
time python3 my_script.py
The output includes three metrics: - Real time: Total elapsed time. - User time: CPU time spent in user-mode. - Sys time: CPU time spent in kernel-mode.
Example output:
real 0m1.023s
user 0m0.912s
sys 0m0.108s
timeit: Use for precise timing of small code snippets or functions within Python scripts.time: Use for measuring the execution time of entire scripts or commands from the command line.Both Python’s timeit and Bash’s time are powerful tools for timing code execution. By understanding their strengths and use cases, developers can effectively measure and optimize the performance of their code.