//有时候,我们想知道一个函数的计算耗时,那么,你可以用timeit
//test.py
1 import timeit
2
3 def func():
4 s = 0
5 for i in range(1000):
6 s += i
7 pass
8
9 def test_range(n):
10 for i in range(n):
11 pass
12
13 def test_xrange(n):
14 for i in xrange(n):
15 pass
16 t = timeit.timeit('test_range(100)', 'from __main__ import test_range', number=1000)
17 print(t)
18 t = timeit.timeit('test_range(100)', 'from __main__ import test_range', number=10000)
19 print(t)
20 t = timeit.timeit('test_xrange(100)', 'from __main__ import test_xrange', number=10000)
21 print (t)
//result
# python test.py
0.00116419792175
0.0125250816345
0.0108740329742
Finally:
xrange比range要快