Sling Academy
Home/Python/Python: 2 Ways to Measure the Execution Time of Code

Python: 2 Ways to Measure the Execution Time of Code

Last updated: June 17, 2023

This concise, practical article will walk you through a couple of different ways to measure the time it takes to execute a piece of code in Python. Without any further ado (like explaining what Python is or talking about its history), let’s get started.

Using the timeit.timeit() function

This approach uses the timeit.timeit() function to get the execution time in seconds with very high accuracy and repeatability. It is recommended for benchmarking and testing small pieces of code.

Syntax:

timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)

Where:

  • stmt (optional): Specifies the code statement or function that you want to measure the execution time. It can be a string of code or a callable object (function). The default value is pass, which is a placeholder statement that does nothing.
  • setup (optional): Specifies the setup code that will be executed before the statement. It can also be a string or a callable object. The default value is pass, indicating no setup code is required.
  • timer (optional): Specifies the timer function to be used for timing. By default, it uses the default timer provided by the timeit module.
  • number (optional): Specifies the number of times the statement should be executed. The default value is 1000000.
  • globals (optional): A dictionary containing global variables. By default, it uses the current global namespace.

The returned value is the total time in seconds taken to execute the statement number times. There is one more thing you need to know is that the timeit module automatically disables the garbage collector during the timing to ensure accurate measurement.

Example:

import timeit

# define a functiom to measure execution time
def my_function():
    for i in range(100000):
        i = i * 2

execution_time = timeit.timeit(my_function, number=1)
print(f"Execution time: {execution_time} seconds")

My output (yours might be different from mine):

Execution time: 0.003365917000337504 seconds

Another example:

import timeit

# This piece of code will be measured 1000 times
piece_of_code = """
str = 'Welcome to Sling Academy!'
words = str.split()
words.reverse()
"""

execution_time = timeit.timeit(piece_of_code, number=1000)
print(f"Execution time: {execution_time} seconds")

Output:

Execution time: 0.00016250000044237822 seconds

Using the time.time() function

The idea of this approach is to use the time.time() function from the time module to calculate the elapsed wall-clock time between two points. It is intuitive and simple but less precise than the preceding technique.

The steps are:

  1. import the time module.
  2. Store the current time before executing the code: start_time = time.time()
  3. Execute the code that you want to measure.
  4. Store the current time after executing the code: end_time = time.time()
  5. Subtract the start time from the end time to get the elapsed time: elapsed = end_time - start_time.

Code example:

import time

start_time = time.time()

# Code to be measured
for i in range(1000000):
    i = i * i * i

end_time = time.time()

elapsed = end_time - start_time
print(f"Execution time: {elapsed} seconds")

Output (yours might be different from mine since we use different computers):

Execution time: 0.08830976486206055 seconds

Conclusion

We’ve seen more than one technique to know the execution time of a function or a piece of code in Python. Some benefits of this knowledge are:

  • Performance optimization: It helps identify slow or inefficient parts of your code, allowing you to focus on optimizing those areas.
  • Algorithm comparison: It allows you to compare the performance of different algorithms or implementations and choose the most efficient one.
  • Benchmarking: You can evaluate the impact of code changes or different configurations on the execution time.
  • Profiling: It helps pinpoint bottlenecks and areas that require optimization in large-scale applications.
  • Debugging: It can reveal unexpected delays or unexpected behavior caused by inefficient code.

This tutorial ends here. If you have any questions, please comment. Happy coding & have a nice day!

Next Article: Python Linked Lists: Explanation & Examples

Previous Article: Working with the pprint.pprint() function in Python (with examples)

Series: Basic Python Tutorials

Python

You May Also Like

  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots
  • Monitoring Order Book Imbalances for Trading Signals via cryptofeed
  • Detecting Arbitrage Opportunities Across Exchanges with cryptofeed