- 論壇徽章:
- 1
|
下面的測試閉包比協(xié)程快,閉包應(yīng)用起來較方便,協(xié)程有個啟動與退出問題,只是個人見解- #!/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() :# 協(xié)程
- 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()
-
復(fù)制代碼 |
評分
-
查看全部評分
|