gevent常用用法
Posted zhouzetian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()
以上是关于gevent常用用法的主要内容,如果未能解决你的问题,请参考以下文章
Process类,Thread类,Pool类,gevent类,ProcessPoolExecutor,ThreadPoolExecutor的用法比较