Python
program execution time
performance measurement
time tracking
code optimization

How do I get time of a Python program's execution?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Understanding the execution time of a Python program is crucial for optimizing performance, identifying bottlenecks, and making informed decisions to enhance efficiency. In this article, we will explore several methods to measure the execution time of a Python script or specific code blocks using built-in modules and third-party libraries. We'll provide code examples and a table summarizing the key points for easy reference.

Using the time Module

The time module provides various time-related functions. The most straightforward method to measure execution time is using time.time(), which returns the current time in seconds since the epoch (January 1, 1970).

Example

python
1import time
2
3start_time = time.time()
4
5# Your code block
6for i in range(100000):
7    pass
8
9end_time = time.time()
10execution_time = end_time - start_time
11
12print(f"Execution time: {execution_time} seconds")

Explanation

  • start_time: Captures the time before the code block starts executing.
  • end_time: Captures the time after the code block has executed.
  • execution_time: Represents the difference between end_time and start_time, providing the total time taken for execution.

Using the timeit Module

The timeit module offers a high-precision method to measure execution time, especially for small code snippets. It automatically performs multiple loops and provides the minimum execution time, which helps to mitigate the effects of background processes.

Example

python
1import timeit
2
3code_to_test = """
4a = 0
5for i in range(100000):
6    a += i
7"""
8
9execution_time = timeit.timeit(stmt=code_to_test, number=100)
10
11print(f"Average execution time: {execution_time / 100} seconds")

Explanation

  • stmt: The code you want to test, provided as a string.
  • number: The number of times the code will be executed.
  • timeit.timeit: Returns the total time taken to execute the code number times. By dividing this by number, you obtain the average execution time for a single execution.

Using datetime for More Precision

The datetime module can be utilized to measure execution times with microsecond precision. This is useful when you require higher accuracy, though it is less precise than timeit for timing small code snippets.

Example

python
1from datetime import datetime
2
3start_time = datetime.now()
4
5# Your code block
6a = [i for i in range(100000)]
7
8end_time = datetime.now()
9execution_time = end_time - start_time
10
11print(f"Execution time: {execution_time.total_seconds()} seconds")

Explanation

  • datetime.now(): Captures the current date and time with microsecond precision.
  • total_seconds(): Converts timedelta to seconds.

Using Profiling with cProfile

cProfile is a built-in profiler that not only provides execution time but also gives detailed information about the function calls in your code.

Example

python
1import cProfile
2import re
3
4def sample_function():
5    a = [i * i for i in range(10000)]
6    return a
7
8cProfile.run('sample_function()')

Explanation

  • cProfile.run(): Runs the specified statement and prints a report including method call count, cumulative time, and more.

Summary Table

MethodPrecisionProsCons
time.time()SecondsSimple and easy to useLimited precision
timeitHigh precisionIdeal for micro-benchmarkingOverhead of loops
datetime.now()MicrosecondsSimple usage, higher than timeLess accurate than timeit
cProfileDetailed reportComprehensive profiling dataOverhead of profiling

Additional Tips

  • When using timeit, avoid using the default shell mode as it might introduce biases. Instead, use it within scripts.
  • Consider the environmental variables and background processes that might affect the timing results.
  • For extensive profiling and visualization, third-party libraries like line_profiler or memory_profiler can offer additional insights along with cProfile.

By integrating these techniques into your development process, you can ensure your Python programs are running optimally and efficiently.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.