python 异步编程 asyncio
import datetime import time import asyncio import numba as nb import numpy as np @nb.jit() def f(n): if n<2: return 1 else: return f(n-1)+f(n-2) async def fun(m): asyncio.sleep(0.1) return '输出{}'.format(i) loop = asyncio.get_event_loop() st = time.time() for i in range(41000): s = loop.run_until_complete(fun(i)) # print(s,' ',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) st2 = time.time() print('异步编程用时:',st2-st,' s') def fun2(m): time.sleep(0.1) return '输出{}'.format(i) for i in range(41): s = fun2(i) # print(s, ' ', time.time()) print('同步编程用时:',time.time()-st2,' s')
1、异步封装
# conding:utf-8 import platform import asyncio import numba as nb class get_asy_result(): _tank = None _bol = True if float(platform.python_version()[:3])>=3.7 else False _pool = asyncio.get_event_loop() @classmethod async def _mains(cls): return await asyncio.gather(*cls._tank) @classmethod def run(cls,*tank): print(type(tank)) cls._tank = tank if cls._bol: return asyncio.run(cls._mains()) else: return cls._pool.run_until_complete(cls._mains()) @nb.jit() def fn(n): if n < 2: return 1 else: return fn(n - 1) + fn(n - 2)
2、调用测试
import asyncio import time from asy import get_asy_result,fn async def factorial(name, number): f = 1 for i in range(1, number + 1): print(f"Task {name}: Compute factorial({i})...") await asyncio.sleep(0.1) f += fn(i) print(f"Task {name}: factorial({number}) = {f}") return f if __name__=="__main__": import platform print(platform.python_version()[:3]) loop = asyncio.get_event_loop() st = time.time() # s = asyncio.run(mains()) # s = loop.run_until_complete(mains()) tk = [factorial("A", 40),factorial("B", 30),factorial("C", 20)] # tk = factorial("C", 3) s = get_asy_result.run(*tk) print(s) print(time.time()-st)
自动化学习。