小编b_a*_*ies的帖子

为什么我的 python 脚本的异步版本不比同步版本快?

我刚刚开始尝试 python 中的 asyncio 库。我的目的是加快我的代码速度,但是对于我的第一个脚本来说,确实没有比不使用 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()
Run Code Online (Sandbox Code Playgroud)

如果我比较它而不对其进行异步编码:

from yahoo_fin import …
Run Code Online (Sandbox Code Playgroud)

python python-asyncio

1
推荐指数
1
解决办法
1222
查看次数

标签 统计

python ×1

python-asyncio ×1