Python 自带计时工具 timeit

jopen 12年前

Python 自带计时工具 timeit


Timer 类:
__init__(stmt="pass", setup="pass", timer=default_timer)
    stmt 是执行语句,setup 是导入执行语句环境
print_exc(file=None)
timeit(number=default_number)
    返回测试所用秒数,number 是每个测试中调用被计时语句的次数
repeat(repeat=default_repeat, number=default_number)
    返回测试所用秒数列表,repeat 是重复整个测试的次数,number 是每个测试中执行语句的次数
快捷方法:
timeit(stmt="pass", setup="pass", timer=default_timer, number=default_number)
    = Timer(stmt, setup, timer).timeit(number)
repeat(stmt="pass", setup="pass", timer=default_timer, repeat=default_repeat, number=default_number)
    = Timer(stmt, setup, timer).repeat(repeat, number)

default_timer 在 win32 下是 time.clock(),在 linux 下是 time.time()
default_number = 1000000
default_repeat = 3
</div>

实例:
import timeit    def func1(x):      pow(x, 2)    def func2(x):      return x * x    v = 10000    func1_test = 'func1(' + str(v) + ')'  func2_test = 'func2(' + str(v) + ')'    print timeit.timeit(func1_test, 'from __main__ import func1')  print timeit.timeit(func2_test, 'from __main__ import func2')    print timeit.repeat(func1_test, 'from __main__ import func1')  print timeit.repeat(func2_test, 'from __main__ import func2')
Python 自带计时工具 timeit


实例2:
#! /usr/bin/env python  # -*- coding: u8 -*-  import random  import timeit    def randDiff( k,n ):      '产生k个不相等的从1到n的随机数'      p = []      y1 = [random.randrange(1,n+1) for i in range(n)]      y2 = []      y2.extend(y1)      y1.sort()      for j in range(k):          temp1 = y1[j]          temp2 = y2.index(temp1)          p.append(temp2 + 1)          y2[temp2] = -1      return p    def randDif(k,n):      '新函数,生成k个1到n之间不相等的随机数'      if k>n:          return []      a = range(1,n+1)      random.shuffle(a)      return a[:k]      if __name__=='__main__':      print timeit.repeat("randDiff(3, 10)", "from __main__ import randDiff", timeit.default_timer, 3, 10000)      print timeit.repeat("randDif(3, 10)", "from __main__ import randDif", timeit.default_timer, 3, 10000)
Python 自带计时工具 timeit