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.
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
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_timeandstart_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
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 codenumbertimes. By dividing this bynumber, 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
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
Explanation
cProfile.run(): Runs the specified statement and prints a report including method call count, cumulative time, and more.
Summary Table
| Method | Precision | Pros | Cons |
time.time() | Seconds | Simple and easy to use | Limited precision |
timeit | High precision | Ideal for micro-benchmarking | Overhead of loops |
datetime.now() | Microseconds | Simple usage, higher than time | Less accurate than timeit |
cProfile | Detailed report | Comprehensive profiling data | Overhead 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
- How do I implement an Objective-C singleton that is compatible with ARC?
- How do I import local fonts async?
- How do I improve ASP.NET MVC application performance?
- How do I iterate through two lists in parallel?
- How do I get user IP address in Django?
- How do I handle the window close event in Tkinter?
- How do I keep track of the time the CPU is used vs the GPUs for deep learning?
- How do I know I've hit the threads limit defined in Node?

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