I'm just starting experimenting with the asyncio library in python. My purpose is to speed up my code, however with my first script there really is no improvement than doing it without asyncio.
from yahoo_fin import stock_info as si
from yahoo_fin.stock_info import *
import time
import asyncio
async def price(stock):
prijs = str(si.get_live_price(stock))
await asyncio.sleep(0.001)
print(prijs)
def main():
loop = asyncio.get_event_loop()
t0 = time.time()
task = asyncio.gather(
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('adbe'),
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('adbe')
)
loop.run_until_complete(task)
t1 = time.time()
print("took %.2f ms" % (1000*(t1-t0)))
if __name__ == '__main__':
main()
If I compare it without coding it asynchronous:
from yahoo_fin import stock_info as si
from yahoo_fin.stock_info import *
import time
import asyncio
def price(stock):
prijs = str(si.get_live_price(stock))
print(prijs)
def main():
t0 = time.time()
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('adbe'),
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('aapl'),
price('fcx'),
price('acn'),
price('adbe')
t1 = time.time()
print("took %.2f ms" % (1000*(t1-t0)))
if __name__ == '__main__':
main()
I would think that the asynchronous version runs all the price() calls at the same time thus reducing the time to execute the program? Am i doing something wrong?
Thanks
str(si.get_live_price(stock))isn't parallelized.