Measuring Code Execution Time Using Pythons timeit
In Python, quantifying the execution duration of code segments is crucial for performance testing. This article explores how to leverage Pythons timeit module for this task.
Example Use Case
Consider the following Python script that executes multiple queries on a database:
<code class="python">conn = ibm_db.pconnect("dsn=myDB", "usrname", "secretPWD") for r in range(5): print "Run %s\n" % r query_stmt = ibm_db.prepare(conn, update) ibm_db.execute(query_stmt) ibm_db.close(conn)</code>
To measure the execution time of the queries, we can employ Pythons timeit module.
Using timeit
Step 1: Import the timeit Module
<code class="python">import timeit</code>
Step 2: Define the Code to Time
Create a string or function that encapsulates the code whose execution time needs to be measured:
<code class="python">setup_code = """ import ibm_db conn = ibm_db.pconnect("dsn=myDB","usrname","secretPWD") query_stmt = ibm_db.prepare(conn, update) """ code_to_time = """ ibm_db.execute(query_stmt) """</code>
Step 3: Set Configuration Parameters
Specify the number of repetitions and iterations for the timeit function:
<code class="python">repetitions = 5 iterations = 100</code>
Step 4: Measure the Execution Time
<code class="python">timeit_result = timeit.timeit(code_to_time, setup=setup_code, number=iterations, globals=globals())</code>
Step 5: Output the Result
<code class="python">print("Execution time:", timeit_result)</code>
Additional Considerations
By following these steps, you can accurately time code segments in your Python scripts and gain insights into their performance characteristics.
The above is the detailed content of How can I use Python's `timeit` module to measure the execution time of code segments?. For more information, please follow other related articles on the PHP Chinese website!