zoukankan      html  css  js  c++  java
  • 协程小示例

    #!/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

  • 相关阅读:
    float浮动
    数据库基础操作
    Python re 模块
    I/O模型的使用
    函数形参与实参
    内置函数重写_运算符重载
    导入模块_导入包_标准库模块
    异常处理
    闭包
    函数式编程
  • 原文地址:https://www.cnblogs.com/fmgao-technology/p/9199173.html
Copyright © 2011-2022 走看看