小编Sin*_*eri的帖子

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: …
Run Code Online (Sandbox Code Playgroud)

python python-asyncio python-aiofiles

4
推荐指数
1
解决办法
3184
查看次数

标签 统计

python ×1

python-aiofiles ×1

python-asyncio ×1