协程小示例

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/6/19 15:03
# @File    : 协程.py


# 协程:单线程下实现并发
import time


def producer():
    g = consumer()
    next(g)
    for i in range(10000000):
        g.send(i)


def consumer():
    while True:
        res = yield


start_time = time.time()
producer()
stop_time = time.time()
print('并发:', stop_time - start_time)  # 并发: 4.239000082015991


# 串行
import time


def producer():
    res = []
    for i in range(10000000):
        res.append(i)
    return res


def consumer(res):
    pass


start_time = time.time()
res = producer()
consumer(res)
stop_time = time.time()
print('串行', stop_time - start_time)  # 串行 2.4110000133514404

原文地址:https://www.cnblogs.com/fmgao-technology/p/9199173.html