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>
之后,您需要设置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中文网其他相关文章!