python3 协程函数yeild

# -*- coding: utf-8 -*-
import time


def consumer(item):
    time.sleep(0.01)
    pass


def producer(target, seq):
    for item in seq:
        target(item)


start_time = time.time()
producer(consumer, range(1000))
print("正常执行时间:%s" % (time.time() - start_time))

# 正常执行时间:10.000572204589844


def consumer():
    time.sleep(0.01)
    while 1:
        item = yield


def producer(target, seq):
    for item in seq:
        target.send(item)


start_time = time.time()
g = consumer()  # 生成器函数
next(g)
producer(g, range(10000000))
print("协程函数执行时间:%s" % (time.time() - start_time))

# 协程函数执行时间:1.921109676361084

 

posted on 2019-06-16 22:41  lilyxiaoyy  阅读(229)  评论(0编辑  收藏  举报

返回
顶部