# _*_ coding: utf-8 _*_
import asyncio
from pprint import pprint
import time
async def add(a, b, c): return a+b+c
async def concat(a, b): return a+b
async def even(l): return [x for x in l if not x%2]
async def split(s): return s.split()
async def int_list(s): return [int(c) for c in s]
d = { add:(3,4,5),
concat:('Lill', 'Klas'),
even:[[1,2,3,4,5,6,7,8,9]],
split:['ett två tre fyra'],
int_list:['12345']
}
async def run(dic):
return {k.__name__:await asyncio.gather(k(*v,)) for k, v in dic.items()}
start=time.perf_counter()
res = asyncio.run(run(d))
end=time.perf_counter()
pprint(res)
print(end-start)
The code is running three times slower than without the async. And I can't figure out what I am doing wrong. I am running python 3.10.5.
no async: 0.00033 async 0.00098
for i in range(1000):around the one timed line actually makes the differences more obvious; it's roughly a factor of 100 difference. That said, structuring it that way means you are setting up and tearing down the event loop every time, which is a huge overhead expense you'd never pay in realasynciocode.gathercall (you only have one thing toawait, sogatherdoes nothing) is responsible for nearly a third of the time of theasynccode. You seem to be going out of your way to make the code slower.