python中计时工具timeit模块的基本用法 分类: python python基础学习 2013-08-08 10:05 2072人阅读 评论(0) 收藏
测试一行代码的运行时间,在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)
实例:
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')
实例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)
看个例子吧
- >>> import timeit
- #执行命令
- >>> t2 = timeit.Timer('x=range(1000)')
- #显示时间
- >>> t2.timeit()
- 10.620039563513103
- #执行命令
- >>> t1 = timeit.Timer('sum(x)', 'x = (i for i in range(1000))')
- #显示时间
- >>> t1.timeit()
- 0.1881566039438201
或者如下使用
- In [1]: from timeit import timeit as timeit
- In [2]: timeit('x=1')
- Out[2]: 0.03820111778328037
- In [3]: timeit('x=map(lambda x:x*10,range(32))')
- Out[3]: 8.05639690328919
其实在ipython中可以直接使用
- In [4]: timeit y=map(lambda x:x**10,range(32))
- 10000000 loops, best of 3: 16.2 ns per loop
在python中编程,最大的乐趣就是实际自己需要实现的东西很少.