如何使用Python的timeit计时代码段以测试性能? [英] How can I time a code segment for testing performance with Pythons timeit?

查看:148
本文介绍了如何使用Python的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\n" % 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.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).在这种情况下,或者如果要平均几次运行所花费的时间,则必须多次手动调用该函数(就像我在示例代码中已经做过的那样,并且当设置其 number 时,timeit会自动执行) 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆