How to Measure Execution Time of Code in Python

In the world of programming, optimizing code for efficiency is crucial. One of the key metrics for assessing code efficiency is execution time. Knowing how to measure the time it takes for your Python code to run can help you identify bottlenecks, optimize performance, and deliver a better user experience. In this post, we’ll explore various methods and tools to measure the execution time of code in Python.

Method 1: Using the time Module:

The simplest way to measure execution time is by using the time module in Python. Here’s a basic example:

Python Code

import time

start_time = time.time()

# Your code here

end_time = time.time()
execution_time = end_time – start_time

print(f”Execution time: {execution_time} seconds”)

This method measures the time in seconds from the start of your code block to its end.

Method 2: Using the timeit Module:

The timeit module provides a more precise and flexible way to measure execution time. It’s particularly useful for benchmarking code and comparing different implementations. Here’s an example:

Python Code:

import timeit

def my_function():
# Your code here

execution_time = timeit.timeit(my_function, number=1000) # Run the function 1000 times
print(f”Average execution time: {execution_time} seconds”)

The timeit module automatically runs your code multiple times and calculates the average execution time.

Method 3: Using the %%timeit Magic Command (Jupyter Notebook):

If you’re using Jupyter Notebook, you can use the %%timeit magic command to measure execution time conveniently. Simply add %%timeit at the beginning of a cell:

Python Code:

%%timeit

# Your code here

Jupyter Notebook will automatically run the code snippet multiple times and display the average execution time.

Method 4: Profiling with cProfile:

The cProfile module allows you to profile your code to see which functions consume the most time. Here’s how you can use it:

Python Code:

import cProfile

def my_function():
# Your code here

if __name__ == “__main__”:
cProfile.run(“my_function()”)

This will provide detailed information about the function calls and their execution times.

Method 5: Using Third-Party Profiling Tools:

There are third-party profiling tools like line_profiler and Pyflame that offer more advanced profiling capabilities, allowing you to analyze code line by line and identify performance bottlenecks.

Real Time Example with Python Code (Using Method 1):

import pandas as pd
import time

import pandas as pd
import time

# create a sample data frame with an integer column
df = pd.DataFrame({'id': [1, 2, 3, 4, 5]*50000})

# Method 1: Using the astype() method
start_time = time.time()
df['id'] = df['id'].astype(str)
method1_time = time.time() - start_time
print("Time taken for Method 1: ", method1_time)

# Method 2: Using the apply() method
start_time = time.time()
int_to_str = lambda x: str(x)
df['id'] = df['id'].apply(int_to_str)
method2_time = time.time() - start_time
print("Time taken for Method 2: ", method2_time)

# Method 3: Using the map() method
start_time = time.time()
int_to_str = lambda x: str(x)
df['id'] = df['id'].map(int_to_str)
method3_time = time.time() - start_time
print("Time taken for Method 3: ", method3_time)

# Method 4: Using the list comprehension
start_time = time.time()
str_list = [str(i) for i in df['id']]
df['id'] = str_list
method4_time = time.time() - start_time
print("Time taken for Method 4: ", method4_time)

# Determine the fastest method
times = {'Method 1': method1_time,
'Method 2': method2_time,
'Method 3': method3_time,
'Method 4': method4_time}
fastest_method = min(times, key=times.get)
print("The fastest method is:", fastest_method)

#Output:
Time taken for Method 1: 0.03693246841430664
Time taken for Method 2: 0.023466110229492188
Time taken for Method 3: 0.02350783348083496
Time taken for Method 4: 0.027480602264404297
The fastest method is: Method 3

Measuring the execution time of your Python code is a fundamental step in optimizing its performance. Whether you use the built-in time and timeit modules, Jupyter Notebook’s %%timeit magic command, or more advanced profiling tools like cProfile, understanding how to assess execution time is essential for writing efficient and responsive Python applications. By profiling your code and identifying areas that need optimization, you can ensure that your Python programs run smoothly and efficiently. If you want to get updated, like the facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.

Add a Comment