范例
AsyncClient使用范例
import pyTSL
import asyncio
import datetime as dt
c = pyTSL.AsyncClient("test.ini")
code = '''
Sleep(1000);
return "OK";
'''
async def main():
assert await c.login()
t0 = dt.datetime.now()
r1 = await c.exec(code)
r2 = await c.exec(code)
print([r1.value(), r2.value()])
print(dt.datetime.now() - t0)
t0 = dt.datetime.now()
L = await asyncio.gather( # 并发执行2个异步任务
c.exec(code),
c.exec(code))
print([ r.value() for r in L])
print(dt.datetime.now() - t0)
asyncio.run(main())
打印:
['OK', 'OK']
0:00:02.476357
['OK', 'OK']
0:00:01.109099
每个任务都需要花费1秒,如果顺序执行2个任务需要2秒,并发执行2个任务只需要1秒。
async_util使用范例
import pyTSL
import asyncio
import datetime as dt
from pyTSL.async_util import *
c = pyTSL.Client("test.ini")
code = '''
Sleep(1000);
return "OK";
'''
async def main():
assert await async_login(c)
t0 = dt.datetime.now()
r1 = await async_exec(c, code)
r2 = await async_exec(c, code)
print([r1.value(), r2.value()])
print(dt.datetime.now() - t0)
t0 = dt.datetime.now()
L = await asyncio.gather( # 并发执行2个异步任务
async_exec(c, code),
async_exec(c, code))
print([ r.value() for r in L])
print(dt.datetime.now() - t0)
asyncio.run(main())