How to check the execution time of Python script?

Measuring execution time is crucial for optimizing Python scripts and identifying performance bottlenecks. Python provides several built-in modules like time, timeit, and cProfile to measure how long your code takes to run.

Using the time Module

The time module provides a simple way to measure execution time by recording start and end timestamps. The time() function returns the current time in seconds since the Unix epoch ?

Example

import time

# Record start time
start_time = time.time()

# Code to measure
numbers = []
for i in range(100000):
    numbers.append(i * 2)

# Record end time
end_time = time.time()

# Calculate execution time
execution_time = end_time - start_time
print(f"Execution time: {execution_time:.6f} seconds")
Execution time: 0.012045 seconds

Example with String Operations

import time

start_time = time.time()

# String concatenation example
statement = "Python is the most popular programming language"
result = statement.upper() + " for data science and web development"
print(result)

end_time = time.time()
execution_time = end_time - start_time
print(f"Execution time: {execution_time:.6f} seconds")
PYTHON IS THE MOST POPULAR PROGRAMMING LANGUAGE for data science and web development
Execution time: 0.000012 seconds

Using the timeit Module

The timeit module provides more accurate measurements by running code multiple times and calculating the average. This reduces the impact of system variations and gives more reliable results ?

Example

import timeit

# Measure list comprehension performance
code_to_test = """
result = [i * 2 for i in range(1000)]
"""

execution_time = timeit.timeit(code_to_test, number=1000)
print(f"Average execution time: {execution_time:.6f} seconds")
print(f"Time per iteration: {execution_time/1000:.9f} seconds")
Average execution time: 0.024156 seconds
Time per iteration: 0.000024156 seconds

Comparing Different Approaches

import timeit

# Compare list comprehension vs regular loop
list_comp = timeit.timeit('[i*2 for i in range(1000)]', number=1000)
regular_loop = timeit.timeit('result=[]\nfor i in range(1000):\n    result.append(i*2)', number=1000)

print(f"List comprehension: {list_comp:.6f} seconds")
print(f"Regular loop: {regular_loop:.6f} seconds")
print(f"List comprehension is {regular_loop/list_comp:.2f}x faster")
List comprehension: 0.024156 seconds
Regular loop: 0.036421 seconds
List comprehension is 1.51x faster

Using cProfile Module

The cProfile module provides detailed profiling information, showing execution time for each function call. This is useful for identifying which parts of your code consume the most time ?

Example

import cProfile

def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

def calculate_fibonacci():
    result = fibonacci(20)
    print(f"Fibonacci(20) = {result}")

# Profile the function
cProfile.run('calculate_fibonacci()')
Fibonacci(20) = 6765
         21893 function calls (21 primitive calls) in 0.008 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.008    0.008 <string>:1(<module>)
        1    0.000    0.000    0.008    0.008 <stdin>:6(calculate_fibonacci)
21891/1    0.008    0.000    0.008    0.008 <stdin>:1(fibonacci)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {built-in method builtins.print}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Comparison of Methods

Module Accuracy Best For Additional Info
time Basic Simple timing measurements Single execution timing
timeit High Benchmarking small code snippets Multiple runs, averaged results
cProfile Detailed Function-level profiling Shows function call statistics

Conclusion

Use time module for basic execution timing, timeit for accurate benchmarking of small code snippets, and cProfile for detailed function-level profiling. Each method serves different optimization needs in Python development.

Updated on: 2026-03-27T11:35:47+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements