首頁  >  文章  >  後端開發  >  如何使用「timeit」模組測量 Python 中程式碼段的執行時間?

如何使用「timeit」模組測量 Python 中程式碼段的執行時間?

Susan Sarandon
Susan Sarandon原創
2024-11-04 20:19:02506瀏覽

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,.

To obtain precise measurements of code performance, svidences times 片語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 utize time in your 🎜>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>
之後,您需要設定timer物件以執行多次查詢以獲得平均時間:

<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>
最後,您可以將平均查詢時間寫入results_update.txt檔案:

<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>
透過使用timeit,您現在可以準確地度量您的查詢效能,並根據需要調整索引和最佳化選項以提高其效率。

以上是如何使用「timeit」模組測量 Python 中程式碼段的執行時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn