|
发表于 2018-5-8 10:35:40
|
显示全部楼层
小甲鱼老师,我有个问题:使用timeit模块测量小段代码的执行时间,特别是对多行代码的时候,使用“”“多行代码”“”这种方式赋值stmt,相比于使用setup和globals设置命名空间的测量时间都小。这是为什么,同样的代码测量的执行时间却大不一样!代码如下所示
- >>> s = """
- class A:
- def func1(self):
- for x in range(100):
- self.count += x
- return self.count
- def __init__(self):
- self.count = 0
- a = A()
- a.func1()
- """
- >>> timeit.timeit(stmt=s, number=100000)
- 2.182303924016196
- >>> a
- <__main__.A object at 0x03207D70>
- >>> timeit.timeit(stmt = "func1()", setup = 'from __main__ import func1 ')
- 4.584396307330735
- >>> timeit.timeit(stmt = "func1()", setup = 'from __main__ import func1 ')
- 4.5826148827454745
- >>> repeat(stmt = "func1()", setup = 'from __main__ import func1 ')
- Traceback (most recent call last):
- File "<pyshell#83>", line 1, in <module>
- repeat(stmt = "func1()", setup = 'from __main__ import func1 ')
- NameError: name 'repeat' is not defined
- >>> timeit.repeat(stmt = "func1()", setup = 'from __main__ import func1 ')
- [4.566492185809238, 4.564154308761772, 4.560875233704792]
- >>> timeit('a.func1()',globals = globals())
- Traceback (most recent call last):
- File "<pyshell#85>", line 1, in <module>
- timeit('a.func1()',globals = globals())
- TypeError: 'module' object is not callable
- >>> a
- <__main__.A object at 0x03207D70>
- >>> a.func1()
- 14850
- >>> timeit.timeit('a.func1()',globals = globals())
- 14.001687110608145
复制代码 |
|