Learn how to measure elapsed time in Python and print how long your code takes to run. This guide covers simple methods using Python’s time function to calculate execution time for better performance tracking.
Measuring how long it takes for a function to run is important for improving code performance. Python offers simple ways to track and display the time taken, helping developers spot slow parts and make their code faster. In this guide, we’ll look at easy methods to measure execution time in Python using built-in tools.
Basic Concept of Measuring Elapsed Time in Python – A Real World Analogy
Measuring time in Python is like tracking how long a task takes in real life. Imagine you’re baking a cake. You note the time when you put the cake in the oven, and then check the time when you take it out. The difference between these two times is how long the cake was in the oven, or its “baking time.”
Similarly, in Python, the idea is simple: you record the time when your code starts running and then note it again when it finishes. The difference between the two times is called the “elapsed time.” Python has built-in functions to help you accomplish this.
How to Time How Long a Function Takes to Execute in Python?
In Python, there are multiple ways to time how long a functions or a specific part fo code takes to execute. Those methods are discussed below along with their syntax and exampels codes.
Measuring Elapsed Time with the time Module
The time
module is one of Python’s simplest ways to measure elapsed time. It includes a function called time()
that returns the current time in seconds since a specific date, known as the Unix epoch, which is January 1, 1970. This date was chosen because it marks the beginning of time tracking for Unix-based systems. The Unix epoch serves as a universal “starting point” for calculating elapsed time. It helps all computers use the same starting point to measure and compare times. By having this fixed date, we avoid confusion when different systems might have chosen other starting dates. By recording the start time before the code runs and the end time after execution, you can calculate the elapsed time accurately. This method allows you to measure how long a function or code block takes to execute in Python.
Syntax
import time time.time()
- import time: Allows you to use the
time
module’s functions for measuring and working with time in your code. - time (module): A built-in Python tool for working with time-related tasks.
- .time() (function): Gives the current time in seconds starting from January 1, 1970.
A module is a collection of functions, while a function is a specific task within a module.
Example
In this code, we measure the elapsed time it takes for a loop to run using Python’s time
module. First, we need to import the time
module by using import time
. We then record the current time with time.time()
and store it in start_time
. Next, the program enters a for
loop that iterates 1,000,000 times, but doesn’t do anything inside the loop (it just “passes”). After the loop finishes, we use time.time()
again to get the end time (end_time
). To find out how long the loop took to run, we subtract start_time
from end_time
. Finally, the program prints the execution time in seconds.
import time print("Starting the timer...") start_time = time.time() # Start the timer # Simulate a task by running a loop for i in range(1000000): pass # This loop just runs and does nothing end_time = time.time() # End the timer elapsed_time = end_time - start_time print(f"Elapsed time: {elapsed_time:.4f} seconds")
Output
Starting the timer... Elapsed time: 0.0485 seconds
Using the timeit Module
The timeit
module in Python is great for measuring how long small pieces of code take to run. Unlike time.time()
, which can be affected by your computer’s activity, timeit
runs the code multiple times to get a better average. This helps you measure execution time more accurately. You can use it to find out how to time how long a function takes to execute and calculate elapsed time in seconds. Whether you’re running it in a script or directly in the Python shell, it’s a reliable way to check the performance of your code.
Syntax
import timeit timeit.timeit(stmt='code_to_test', number=any_number)
- import timeit: Allows you to use the
time
it module’s functions for measuring execution time of code snippets. - stmt: The code to be executed, provided as a string.
- number: The number of times to execute
stmt
.
Example
In this example, we start by importing the timeit
module to measure how long a piece of code takes to run. We define the code we want to test as a string because timeit.timeit()
expects the code in this format. The string contains a loop that adds numbers from 0 to 999, performing a task. We use timeit.timeit()
with the stmt
argument, which stands for “statement” and indicates the code block that we want to measure. We also use the number=1000
argument to specify that the code should be executed 1,000 times. This setup helps timeit
run the code repeatedly to get an accurate measure of performance. The result is stored in execution_time
, and we print this value to understand how long the code took to run, helping us evaluate its efficiency.
import timeit # Code to measure code_to_test = ''' total = 0 for i in range(1000): total += i ''' # Measure execution time execution_time = timeit.timeit(stmt=code_to_test, number=1000) # Print the result print(f"Execution time: {execution_time} seconds")
Output
Execution time: 0.09671047600022575 seconds
Using the datetime Module
The datetime
module in Python is useful for handling dates and times in a detailed way. Unlike the time
or timeit
modules, which focus on simpler time measurements or code performance, datetime
lets you measure elapsed time between two events with detailed information like hours, minutes, and seconds. This helps you calculate Python elapsed time more clearly and is great for recording time durations in a format that’s easier to read and use for reporting or debugging. Whether you need to measure how long a function takes or track time in a more detailed manner, datetime
is a flexible choice for handling Python measure time tasks.
Syntax
from datetime import datetime datetime.now()
- from datetime import datetime: This imports the
datetime
class from thedatetime
module, allowing you to create and manipulate date and time objects. - datetime.now(): This method fetches the current local date and time, providing a
datetime
object that includes the current year, month, day, hour, minute, second, and microsecond.
Example
In this example, we use the datetime
module to measure how long a task takes. We begin by importing datetime
and recording the current time before the task starts using datetime.now()
. The task itself is a loop that adds numbers from 0 to 999,999. After the task is completed, the end time is recorded again using datetime.now()
. The difference between the start and end times gives us the elapsed time. Finally, the program prints the duration in a human-readable format, allowing us to see exactly how long the task took in terms of hours, minutes, and seconds.
from datetime import datetime # Record the start time start_time = datetime.now() # Example task: Loop through a list total = 0 for i in range(1000000): total += i # Record the end time end_time = datetime.now() # Calculate the elapsed time elapsed_time = end_time - start_time # Print the elapsed time in a readable format print(f"Elapsed time: {elapsed_time}")
Output
Elapsed time: 0:00:00.073445
Achieving High Precision with perf_counter
The time.perf_counter()
function in Python is perfect for measuring how long something takes with very high accuracy. It’s great for Python measure time tasks, especially when you need to know exactly how long a function takes to run. Unlike time.time()
, which can be affected by system changes, perf_counter()
provides precise and reliable elapsed time in seconds. This makes it ideal for timing small operations and calculating Python elapsed time accurately.
Syntax
import time time.perf_counter()
- import time: Allows you to use the
time
module’s functions for measuring and working with time in your code. - time.perf_counter(): provides a high-precision timer for accurate measurements of time intervals.
Example
The code measures the time it takes to execute a loop that runs one million times. It starts by recording the current time with time.perf_counter()
and stores it as start_time
. After this, the code runs a loop which essentially does nothing but iterate one million times. Once the loop finishes, it records the time again with time.perf_counter()
and stores it as end_time
. By subtracting start_time
from end_time
, it calculates the elapsed time. Finally, it prints this duration showing how long the loop took to run with precise timing.
import time # Start the high-precision timer start_time = time.perf_counter() # Simulate a task by running a loop for i in range(1000000): pass # This loop just runs without any task # Stop the high-precision timer end_time = time.perf_counter() # Calculate the elapsed time elapsed_time = end_time - start_time print(f"Elapsed time: {elapsed_time:.8f} seconds")
Output
Elapsed time: 0.03181160 seconds
Conclusion
Measuring elapsed time in Python is important for understanding and improving code performance. Python provides different ways to do this. For quick checks, you can use time.time()
to measure elapsed time. For more accurate results, timeit
and perf_counter()
are better choices. The datetime
module gives easy-to-read results, while perf_counter()
provides very precise measurements. By using these methods, developers can effectively calculate Python elapsed time, find slow parts of their code, and make improvements to speed up their programs.