使用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
相关产品推荐
相关产品推荐

