Home >Backend Development >Python Tutorial >How can I measure the execution time of a code segment in Python using the `timeit` module?

How can I measure the execution time of a code segment in Python using the `timeit` module?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 20:19:02595browse

How can I measure the execution time of a code segment in Python using the `timeit` module?

Measuring Code Execution Time with Pythons timeit

To obtain precise measurements of code performance, Python offers the timeit module. This module provides a comprehensive set of tools for timing code segments and evaluating their efficiency.

To determine the time required to execute a specific query and output it to a file in your Python script, you can utilize timeit as follows:

Within the code block where the query is executed (currently within the 'for r in range(100):' loop), insert a timeit.Timer object to encapsulate the query execution. For example:

<code class="python">import timeit
...

# Add a timeit timer to measure query execution time
query_stmt = "update TABLE set val = %i where MyCount >= '2010' \
and MyCount < '2012' and number = '250'" % rannumber
timer = timeit.Timer("ibm_db.execute(query_stmt)")
...</code>

After that, you need to set the timer object to run multiple queries to get the average time:

<code class="python">...
# Run the timer multiple times to calculate average time 
# (set the 'number' parameter to adjust the number of runs)
avg_query_time = timer.timeit(number=10)
...</code>

Finally, you can write the average query time to the results_update.txt file:

<code class="python">...
with open("results_update.txt", "a") as myfile:
    myfile.write("Average query execution time: {:.4f} seconds\n".format(avg_query_time))
...</code>

By using timeit, you can now accurately measure your query performance and adjust indexing and optimization options as needed to improve its efficiency.

The above is the detailed content of How can I measure the execution time of a code segment in Python using the `timeit` module?. 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