我有一个python脚本,它的工作就像它应该,但我需要写执行时间。我在谷歌上搜索过我应该使用timeit,但我似乎不能让它工作。

我的Python脚本是这样的:

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所需的时间。目的是用不同的索引和调优机制测试数据库的更新语句。


当前回答

您可以在要计时的块前后使用time.time()或time.clock()。

import time

t0 = time.time()
code_block
t1 = time.time()

total = t1-t0

这个方法不像timeit那样精确(它不平均几次运行),但它很简单。

time.time()(在Windows和Linux中)和time.clock()(在Linux中)对于快速函数来说不够精确(你得到total = 0)。在这种情况下,或者如果你想通过几次运行来平均时间,你必须手动多次调用函数(我认为你已经在你的示例代码中这样做了,当你设置它的number参数时,timeit会自动执行)

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()更受欢迎。

其他回答

如何使用timeit为函数计时:

import timeit

def time_this():
    return 'a' + 'b'

timeit.timeit(time_this, number=1000)

它返回运行time_this() 1000次所花费的时间(以秒为单位)。

如果您正在分析代码,并且可以使用IPython,那么它有一个神奇的函数%timeit。

%%timeit操作在单元格上。

In [2]: %timeit cos(3.14)
10000000 loops, best of 3: 160 ns per loop

In [3]: %%timeit
   ...: cos(3.14)
   ...: x = 2 + 3
   ...: 
10000000 loops, best of 3: 196 ns per loop

另一个简单的timeit例子:

def your_function_to_test():
   # do some stuff...

time_to_run_100_times = timeit.timeit(lambda: your_function_to_test, number=100)

我看到这个问题已经有了答案,但我仍然想补充我的2美分。

我也遇到过类似的情况,我必须测试几种方法的执行时间,因此写了一个小脚本,在其中编写的所有函数上调用timeit。

该脚本也可作为github gist在这里。

希望对你和其他人有所帮助。

from random import random
import types

def list_without_comprehension():
    l = []
    for i in xrange(1000):
        l.append(int(random()*100 % 100))
    return l

def list_with_comprehension():
    # 1K random numbers between 0 to 100
    l = [int(random()*100 % 100) for _ in xrange(1000)]
    return l


# operations on list_without_comprehension
def sort_list_without_comprehension():
    list_without_comprehension().sort()

def reverse_sort_list_without_comprehension():
    list_without_comprehension().sort(reverse=True)

def sorted_list_without_comprehension():
    sorted(list_without_comprehension())


# operations on list_with_comprehension
def sort_list_with_comprehension():
    list_with_comprehension().sort()

def reverse_sort_list_with_comprehension():
    list_with_comprehension().sort(reverse=True)

def sorted_list_with_comprehension():
    sorted(list_with_comprehension())


def main():
    objs = globals()
    funcs = []
    f = open("timeit_demo.sh", "w+")

    for objname in objs:
        if objname != 'main' and type(objs[objname]) == types.FunctionType:
            funcs.append(objname)
    funcs.sort()
    for func in funcs:
        f.write('''echo "Timing: %(funcname)s"
python -m timeit "import timeit_demo; timeit_demo.%(funcname)s();"\n\n
echo "------------------------------------------------------------"
''' % dict(
                funcname = func,
                )
            )

    f.close()

if __name__ == "__main__":
    main()

    from os import system

    #Works only for *nix platforms
    system("/bin/bash timeit_demo.sh")

    #un-comment below for windows
    #system("cmd timeit_demo.sh")

这里有一个简单的包装史蒂文的答案。这个函数不做重复运行/平均,只是节省了你不得不重复计时代码无处不在:)

'''function which prints the wall time it takes to execute the given command'''
def time_func(func, *args): #*args can take 0 or more 
  import time
  start_time = time.time()
  func(*args)
  end_time = time.time()
  print("it took this long to run: {}".format(end_time-start_time))