Timing Code Execution with Python’s timeit and Bash’s time

Author

Andres Monge

Published

December 17, 2024

Measuring 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.

Python’s timeit Module

The 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.

Basic Usage

Here’s how to use timeit to measure the execution time of a Python function:

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.028086 seconds

Key Features

  1. High Precision: timeit uses the most accurate timer available on your system.
  2. Repeatability: It can run the code multiple times to get an average execution time.
  3. Avoids Overhead: It minimizes the impact of setup code on timing results.

Timing Asynchronous Code

For asynchronous code, timeit can be combined with asyncio to measure execution time. Here’s an example:

Code
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())

Bash’s time Command

The 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.

Basic Usage

To measure the execution time of a command, simply prefix it with time:

time python3 my_script.py

Output Example

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

When to Use Each Tool

  1. Python’s timeit: Use for precise timing of small code snippets or functions within Python scripts.
  2. Bash’s time: Use for measuring the execution time of entire scripts or commands from the command line.

Conclusion

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.