admin管理员组

文章数量:1128270

I need to download multiple files at once from MongoDB, and then process the result as soon as file is downloaded. But the thing is, it's not faster of sync cycle. It seems like it still waits for previous to download. Playing with max_workers didn't help.

Each file download elapsed time ~0.3, so I expect it to complete all downloads at once at least at elapsed ~0.5. But it always gives me 3 seconds for 10 files, no matter which way I download it.

I checked it multiple times and can't figure what could be wrong at this point.

I tried AsyncIOMotorClient + AsyncIOMotorGridFSBucket + asyncio, and results are worse - slower.

client = MongoClient(
    host=MONGO_HOST,
    port=MONGO_PORT,
)

db = client[MONGO_DB_NAME]
fs = GridFS(db)


def get_file(file_id: str) -> dict:
    grid_out = fs.get(ObjectId(file_id))
    contents = grid_out.read()
    str_content = contents.decode()
    return json.loads(str_content)


def get_values():

    files_id = [...] # Guids

    # Without concurency
    for file_id in files_id:
        get_file(file_id)  # Each file elapsed ~0.3 seconds

    # !!! Total elapsed time ~3 seconds

    # -----------------------------------

    # With concurency
    with concurrent.futures.ThreadPoolExecutor() as executor:

        futures = []
        for file_id in files_id:
            futures.append(executor.submit(get_file, file_id))

        results = [
            future.result() for future in futures
        ]  # Each file elapsed ~0.3 seconds

    # !!! Total elapsed time ~3 seconds

本文标签: