- 论坛徽章:
- 1
|
下面的测试闭包比协程快,闭包应用起来较方便,协程有个启动与退出问题,只是个人见解- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import time
- class Table:
- __slots__ = ('index','vals')
- def __init__(self):
- self.index = {0:0,3:1,6:2}
- self.vals = [0.36,1.25,2.25]
- def __getitem__(self,mon):
- return self.vals[self.index[mon]]
-
- def timeTest(fn):
- def test(*a,**k):
- tm = time.clock()
- fn(*a,**k)
- print(time.clock()-tm)
- return test
-
- def test_bb(): # 闭包
- s = Table()
- def _index(mon):
- nonlocal s
- try:
- return s[mon]
- except Exception:
- return 0.0
- return _index
- def test_xc() :# 协程
- s = Table()
- item = None
- while True:
- mon = yield item
- try:
- item = s[mon]
- except Exception:
- item = 0.0
- @timeTest
- def get_bb():
- j = 0
- t = test_bb()
- while j < 10000:
- for i in [0,3,6]:
- t(i)
- j += 1
- @timeTest
- def get_xc():
- j = 0
- t = test_xc()
- t.send(None)
- while j < 10000:
- for i in [0,3,6]:
- t.send(i)
- j += 1
- t.close()
-
-
- if __name__ == '__main__':
- get_bb()
- get_xc()
-
复制代码 |
评分
-
查看全部评分
|