CSDN博客地址

gevent常用用法

# 1:单核上的协程
import asyncio
import time

async def test(time):
await asyncio.sleep(time)


async def main():
start_time = time.time()
# 创建任务
tasks = [asyncio.create_task(test(1)) for _ in range(10000)]
# 将任务丢到执行队列里面去
[await t for t in tasks]
print(time.time() - start_time)

if __name__ == "__main__":
asyncio.run(main())


# 多核上的协程:(多进程 + 协程)
from multiprocessing import Pool
import asyncio
import time


async def test1(time):
await asyncio.sleep(time)


async def main1(num):
start_time = time.time()
tasks = [asyncio.create_task(test1(1)) for _ in range(num)]
[await t for t in tasks]
print(time.time() - start_time)


def run(num):
asyncio.run(main1(num))


if __name__ == "__main__":
p = Pool()
for i in range(4):
p.apply_async(run, args=(2500,))
p.close()
p.join()
 
posted @ 2019-12-17 17:12  Yi_warmth  阅读(305)  评论(0编辑  收藏  举报
CSDN博客地址