如何使用 Python 的 timeit 对代码段进行计时以测试性能? [英] How can I time a code segment for testing performance with Pythons timeit?
问题描述
我有一个可以正常工作的 python 脚本,但我需要写下执行时间.我在谷歌上搜索我应该使用 timeit
但是我似乎无法让它工作.
I've a python script which works just as it should, but I need to write the execution time. I've googled that I should use timeit
but I can't seem to get it to work.
我的 Python 脚本如下所示:
My Python script looks like this:
import sys
import getopt
import timeit
import random
import os
import re
import ibm_db
import time
from string import maketrans
myfile = open("results_update.txt", "a")
for r in range(100):
rannumber = random.randint(0, 100)
update = "update TABLE set val = %i where MyCount >= '2010' and MyCount < '2012' and number = '250'" % rannumber
#print rannumber
conn = ibm_db.pconnect("dsn=myDB","usrname","secretPWD")
for r in range(5):
print "Run %s
" % r
ibm_db.execute(query_stmt)
query_stmt = ibm_db.prepare(conn, update)
myfile.close()
ibm_db.close(conn)
我需要的是执行查询并将其写入文件 results_update.txt
所需的时间.目的是用不同的索引和调优机制测试我的数据库的更新语句.
What I need is the time it takes to execute the query and write it to the file results_update.txt
. The purpose is to test an update statement for my database with different indexes and tuning mechanisms.
推荐答案
您可以使用 time.time()
或 time.clock()
要计时的块之前和之后.
You can use time.time()
or time.clock()
before and after the block you want to time.
import time
t0 = time.time()
code_block
t1 = time.time()
total = t1-t0
这种方法不如 timeit
(它不会平均多次运行)但它很简单.
This method is not as exact as timeit
(it does not average several runs) but it is straightforward.
time.time()
(在 Windows 和 Linux 中)和 time.clock()
(在 Linux 中)对于快速函数来说不够精确(你得到 total =0).在这种情况下,或者如果您想平均多次运行所用的时间,您必须多次手动调用该函数(我认为您在示例代码中已经这样做了,并且 timeit 在您设置它的 number 时会自动执行em> 参数)
time.time()
(in Windows and Linux) and time.clock()
(in Linux) are not precise enough for fast functions (you get total = 0). In this case or if you want to average the time elapsed by several runs, you have to manually call the function multiple times (As I think you already do in you example code and timeit does automatically when you set its number argument)
import time
def myfast():
code
n = 10000
t0 = time.time()
for i in range(n): myfast()
t1 = time.time()
total_n = t1-t0
在 Windows 中,正如 Corey 在评论中所述,time.clock()
具有更高的精度(微秒而不是秒)并且优于 time.time()
.
In Windows, as Corey stated in the comment, time.clock()
has much higher precision (microsecond instead of second) and is preferred over time.time()
.
这篇关于如何使用 Python 的 timeit 对代码段进行计时以测试性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!