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

Sin*_*eri 4 python python-asyncio python-aiofiles

我有一个问题,我是 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}')
Run Code Online (Sandbox Code Playgroud)

并得到这个结果:

Asynchronous: Take 0.011
Synchronous: Take 0.001
Run Code Online (Sandbox Code Playgroud)

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

Sin*_*eri 13

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

你没有做错任何事。aiofiles 的作用是将文件读取操作委托给线程池。这种方法会比直接读取文件慢。好处是,当在不同的线程中读取文件时,您的应用程序可以在主线程中执行其他操作。

恐怕还没有真正的跨平台异步读取文件的方法:)

我希望它对遇到同样问题的人有所帮助