Chinaunix

标题: 闭包与协程? [打印本页]

作者: micrchaoo    时间: 2015-12-22 19:15
标题: 闭包与协程?
下面的测试闭包比协程快,闭包应用起来较方便,协程有个启动与退出问题,只是个人见解
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-

  3. import time

  4. class Table:
  5.     __slots__ = ('index','vals')
  6.     def __init__(self):
  7.         self.index = {0:0,3:1,6:2}
  8.         self.vals = [0.36,1.25,2.25]
  9.     def __getitem__(self,mon):
  10.         return self.vals[self.index[mon]]
  11.         
  12. def timeTest(fn):
  13.     def test(*a,**k):
  14.         tm = time.clock()
  15.         fn(*a,**k)
  16.         print(time.clock()-tm)
  17.     return test
  18.    
  19. def test_bb():  # 闭包
  20.     s = Table()
  21.     def _index(mon):
  22.         nonlocal s
  23.         try:
  24.             return s[mon]
  25.         except Exception:
  26.             return 0.0
  27.     return _index

  28. def test_xc()   :# 协程
  29.     s = Table()
  30.     item = None
  31.     while True:
  32.         mon = yield item
  33.         try:
  34.             item = s[mon]
  35.         except Exception:
  36.             item = 0.0
  37. @timeTest         
  38. def get_bb():
  39.     j = 0
  40.     t = test_bb()
  41.     while j < 10000:
  42.         for i in [0,3,6]:
  43.             t(i)
  44.         j += 1
  45. @timeTest
  46. def get_xc():
  47.     j = 0
  48.     t = test_xc()
  49.     t.send(None)
  50.     while j < 10000:
  51.         for i in [0,3,6]:
  52.             t.send(i)
  53.         j += 1
  54.     t.close()
  55.    
  56.   
  57. if __name__ == '__main__':  
  58.     get_bb()
  59.     get_xc()
  60.    
复制代码

作者: substr函数    时间: 2015-12-23 11:38
回复 1# micrchaoo


   
def timeTest(fn):
    def test(*a,**k):
        tm = time.clock()
        fn(*a,**k)
        print(time.clock()-tm)
    return test


写的真好,今天一天都在你这学习,收获颇丰,
先mark一下,以后可能还要参考。
作者: huangxiaohen    时间: 2015-12-23 13:58
本帖最后由 huangxiaohen 于 2015-12-23 14:15 编辑

我是新手,难道用个yield就是协程了?我书读的少,可不要骗我.
除了在twisted以及tornado中的特殊搭配用法外,yield就是个迭代的作用而已。
而且yield的返回值是一个generator,怎么可能拿来直接去字典里当做key去取。
作者: substr函数    时间: 2015-12-23 18:15
回复 3# huangxiaohen

个人见解
可能是这样的:
协程,英文名Coroutine。


co- [together] [协同][协]

test_xc: 生产者协程
get_xc: 消费者协程

协程看上去是子程序,
但执行过程中,
在子程序内部可中断,
然后转而执行别的子程序 (不是函数调用),
在适当的时候再返回来接着执行。




作者: substr函数    时间: 2015-12-23 18:33
回复 3# huangxiaohen


   
而且yield的返回值是一个generator,怎么可能拿来直接去字典里当做key去取。


t = test_xc()
t 是一个generator



mon = yield item


yield的返回值 是 mon

t.send(i) ==> mon
mon 是  i
i 不是一个generator

作者: substr函数    时间: 2015-12-24 10:05
回复 3# huangxiaohen


   
generator,拿来字典里当做key。
也是可以的 [ ]
  1. #!/usr/bin/python2
  2. # coding: utf-8


  3. def G1():
  4.     for i in xrange(3):
  5.         yield i


  6. g = G1()

  7. print g # <generator object G1 at 0x7f85373bd500>


  8. D = {}
  9. D[g] = 5

  10. print D[g]      # 5
  11. print D.keys()  # [<generator object G1 at 0x7f85373bd500>]

复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2