【问题标题】:AIOFiles Take Longer Than Normal File OperationAIOFiles 比正常文件操作花费更长的时间
【发布时间】:2021-08-27 17:11:26
【问题描述】:

我有一个问题,我是 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

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

【问题讨论】:

    标签: python python-asyncio python-aiofiles


    【解决方案1】:

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

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

    目前还没有一种真正的、跨平台的异步读取文件的方法,我'我害怕:)

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

    【讨论】:

      猜你喜欢
      • 2016-04-22
      • 1970-01-01
      • 2020-09-07
      • 2019-11-22
      • 2012-02-18
      • 1970-01-01
      • 2019-10-26
      • 2014-06-19
      • 2013-06-03
      相关资源
      最近更新 更多