gpt4 book ai didi

python - AIOFiles 比正常文件操作花费更长的时间

转载 作者:行者123 更新时间:2023-12-05 00:43:42 54 4
gpt4 key购买 nike

我有一个问题,我是 python 异步世界的新手,我编写了一些代码来测试 asyncio 的功能,我创建了 10 个包含随机内容的文件,名为 file1.txt , file2.txt, ..., file10.txt

这是我的代码:

import asyncio
import aiofiles
import time

async def reader(pack, address):
async with aiofiles.open(address) as file:
pack.append(await file.read())

async def main():
content = []
await asyncio.gather(*(reader(content, f'./file{_+1}.txt') for _ in range(10)))

return content

def core():
content = []
for number in range(10):
with open(f'./file{number+1}.txt') as file:
content.append(file.read())

return content

if __name__ == '__main__':
# Asynchronous
s = time.perf_counter()
content = asyncio.run(main())
e = time.perf_counter()
print(f'Take {e - s: .3f}')

# Synchronous
s = time.perf_counter()
content = core()
e = time.perf_counter()
print(f'Take {e - s: .3f}')

得到了这个结果:

Asynchronous: Take 0.011
Synchronous: Take 0.001

为什么异步代码比同步代码花费更长的时间?我哪里做错了?

最佳答案

我发布了一个问题 #110在 aiofiles 的 GitHub 上,aiofiles 的作者回答说:

You're not doing anything wrong. What aiofiles does is delegate the file reading operations to a thread pool. This approach is going to be slower than just reading the file directly. The benefit is that while the file is being read in a different thread, your application can do something else in the main thread.

A true, cross-platform way of reading files asynchronously is not available yet, I'm afraid :)

希望对遇到同样问题的 friend 有所帮助

关于python - AIOFiles 比正常文件操作花费更长的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68957147/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com