You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用asyncio加载文件的速度对比:同步为何快于异步?

异步IO加载文件比同步版本慢是否正常?

我正在编写一段代码,需要将一个Python集合与其他多个集合进行比较,并保留交集长度最小的文件名。目前已有一个同步版本,但想通过async/await优化性能,于是先对集合加载环节做对比测试:编写脚本将一个小集合写入磁盘,然后读取100次。但意外发现同步版本的速度快很多,这种情况是否正常?还是我的代码存在问题?

同步版本代码

import pickle
import asyncio
import time 
import aiofiles

pickle.dump(set(range(1000)), open('set.pkl', 'wb'))

def count():
    print("Started Loading")
    with open('set.pkl', mode='rb') as f:
        contents = pickle.loads(f.read())
    print("Finishd Loading")

def main():
    for _ in range(100):
        count()

if __name__ == "__main__":
    s = time.perf_counter()
    main()
    elapsed = time.perf_counter() - s
    print(f"{__file__} executed in {elapsed:0.3f} seconds.")

异步版本代码

import pickle
import asyncio
import time 
import aiofiles

pickle.dump(set(range(1000)), open('set.pkl', 'wb'))

async def count():
    print("Started Loading")
    async with aiofiles.open('set.pkl', mode='rb') as f:
        contents = pickle.loads(await f.read())
    print("Finishd Loading")

async def main():
    await asyncio.gather(*(count() for _ in range(100)))

if __name__ == "__main__":
    import time
    s = time.perf_counter()
    asyncio.run(main())
    elapsed = time.perf_counter() - s
    print(f"{__file__} executed in {elapsed:0.3f} seconds.")

执行结果

async.py executed in 0.052 seconds.
sync.py executed in 0.011 seconds.

内容的提问来源于stack exchange,提问作者user3715117

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:50:34