python - 协程的真正的意义在哪里?我写了两个程序对比
PHP中文网
PHP中文网 2017-04-18 09:05:07
0
3
384

我写了两段代码分别执行、
第一段代码:
由廖雪峰老师的程序改编使用了协程的思维

import time

def consumer():
    r = ''
    while True:
        n = yield r
        if not n:
            return
        q = 100
        while q:
            q -= 1
            time.sleep(0.1)
            print('Consumer runing %d...' % q)
        print('[CONSUMER] Consuming %s...' % n)
        r = '200 OK'

def produce(c):
    next(c)
    n = 0
    while n < 5:
        n = n + 1
        q = 100
        while q:
            q -= 1
            time.sleep(0.1)
            print('Loading %d...' % q)
        print('[PRODUCER] Producing %s...' % n)
        r = c.send(n)
        print('[PRODUCER] Consumer return: %s' % r)
    c.close()

if __name__=='__main__':
    start = time.time()
    c = consumer()
    produce(c)
    print('Use time: %.3fs' % (time.time() - start))

第二段用来对比:
自己写了简单的函数调用方法

import time

def consumer(n):
    r = ''
    q = 100
    while q:
        q -= 1
        time.sleep(0.1)
        print('Consumer runing %d...' % q)
    print('[CONSUMER] Consuming %s...' % n)
    return '200 OK'

def produce():
    n = 0
    while n < 5:
        n = n + 1
        q = 100
        while q:
            q -= 1
            time.sleep(0.1)
            print('Loading %d...' % q)
        print('[PRODUCER] Producing %s...' % n)
        r = consumer(n)
        print('[PRODUCER] Consumer return: %s' % r)

if __name__=='__main__':
    start = time.time()
    produce()
    print('Use time: %.3fs' % (time.time() - start))

运行以下可以轻易的发现两段代码所执行的结果是一样的、

第一段代码所花的时间
Use time: 100.310s
第二段代码所花时间
Use time: 100.314s
两段代码花费的时间也差不多

代码量、相差无几

这就让我很头痛了
简单的函数调用是两个函数之间调用并返回相应的数据
而协程写的代码是两个函数之间相互调用、相互传送数据也没有做到两个函数同时进行
那么,协程发明的意义在哪里呢?就仅仅为了这0.004s的时间差么?

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
Ty80

If there is more logic or initialization class code at the beginning of the consumer function, you will know the gap and which way of writing is more convenient.

刘奇

The advantage of coroutines in python is the code consistency of asynchronous operations. There is no asynchronous operation here. The entire thread stops when sleeping

巴扎黑

I recommend that the questioner read this article A Curious Course on Coroutines and Concurrency, although it is a bit old.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template