Home  >  Article  >  Backend Development  >  How can Python's `timeit` module be used to measure code execution time effectively?

How can Python's `timeit` module be used to measure code execution time effectively?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 05:29:02481browse

How can Python's `timeit` module be used to measure code execution time effectively?

Performance Testing with Python's timeit: A Step-by-Step Guide

To determine the execution time of a specific code segment, Python offers the timeit module. Let's explore how to use it effectively.

Consider the following Python script that updates a database table:

<code class="python">import time
import random
import ibm_db

# Open a file for writing results
myfile = open("results_update.txt", "a")

# Create a database connection
conn = ibm_db.pconnect("dsn=myDB", "usrname", "secretPWD")

# Prepare a parameterized update statement
query_stmt = ibm_db.prepare(conn, "update TABLE set val = ? where MyCount >= '2010' and MyCount < '2012' and number = '250'")

# Execute the update statement 100 times with different random values
for r in range(100):
    rannumber = random.randint(0, 100)
    params = [rannumber]
    ibm_db.execute(query_stmt, params)
    myfile.write(str(rannumber) + "\n")

# Close the file and connection
myfile.close()
ibm_db.close(conn)

To time the execution of the inner loop, we can employ time.time() or time.clock(), which return the current time in seconds:

<code class="python">t0 = time.time()  # Start time

# Code to be timed

t1 = time.time()  # End time

total = t1 - t0

However, timeit offers a more comprehensive approach that can average multiple runs and provide more accurate results:

<code class="python">import timeit

setup = """
import random
import ibm_db

conn = ibm_db.pconnect("dsn=myDB", "usrname", "secretPWD")
query_stmt = ibm_db.prepare(conn, "update TABLE set val = ? where MyCount >= '2010' and MyCount < '2012' and number = '250'")
params = [12]
"""

code = """
ibm_db.execute(query_stmt, params)
"""

timeit.Timer(code, setup).timeit(number=100)  # Run the code 100 times</code>

In this code, the setup variable contains the code that needs to be executed before each run, such as initializing the database connection and preparing the statement. The code variable contains the code to be timed. The number argument specifies the number of times the code should be run.

By utilizing the timeit module, you can obtain precise and reliable measurements of code execution times, enabling you to optimize and monitor the performance of your Python applications.

The above is the detailed content of How can Python's `timeit` module be used to measure code execution time effectively?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn