Part 13 / Topic 11 of 11
Putting it together: parallel downloader
The task: download 8 "files" from the local file server (each answer takes 0.3 s) three ways, check that all three got the same contents, and print a timing table.
How it works (examples/08_parallel_downloader.py):
start_server()fromfile_server.pystarts a realhttp.serveron127.0.0.1in a daemon thread (port 0 = any free port).download_sequential()callsfetch()once per URL, one after another.download_threads()usesThreadPoolExecutor(max_workers=4)andpool.map, which keeps the URL order.download_async()usesasyncio.gather+asyncio.to_thread(fetch, url), with aSemaphore(4)so at most 4 requests are in flight.timed()measures each method withtime.perf_counter(); the table shows seconds and the speed-up vs sequential.- The
try/finallymakes sure the server is stopped even if a download fails.
python 08_parallel_downloader.py
Output (time varies):
8 files, 0.3 s each, 4 at a time
Method Seconds Speed-up
Sequential 2.42 1.0x
ThreadPoolExecutor 0.61 4.0x
asyncio + to_thread 0.61 3.9x
Same files every way: True
First file says: contents of report-1.csv
8 files with 4 at a time = 2 "rounds" of 0.3 s, so about 0.6 s. Try WORKERS = 8 and see it drop to about 0.3 s.
Done here? The practice set for Part 13 — 8 exercises with solutions — is on the part page.