Was using the multiprocessing process before async, to test which is faster I am trying to run the code with async, but it gives me an error saying: 'await' outside async.
My code:
import asyncio import time async def sleep(): print(f'Time: {time.time() - start:.2f}') await asyncio.sleep(1) async def sum(name, numbers): def sum_(numbers): total = 0 print(f'Task {name}: Computing {total}+{number}') await sleep() total += number print(f'Task {name}: Sum = {total}\n') for number in numbers: sum_(numbers) start = time.time() loop = asyncio.get_event_loop() tasks = [ loop.create_task(sum("A", [1, 2])), loop.create_task(sum("B", [1, 2, 3])), ] loop.run_until_complete(asyncio.wait(tasks)) loop.close() end = time.time() print(f'Time: {end-start:.2f} sec') Please note: This is just an example of code, in original code I cannot do as per the below:
for number in numbers: sum_(numbers) await sleep() Testing asyncio as advised on this comment
sum_()is not an async function, you can't useawaitin it. Change toasync def sum_(numbers):async def on_ticks(ws, ticks): #await sleep() inside this functionandawait kws.on_ticks = on_ticks, it gave me error: SyntaxError: cannot assign to await expression, full code @Barmarkws.on_ticks = await on_ticks()You useawaitto call an asynchronous function.