feat: Semaine 9
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
# Exercice 2
|
||||
|
||||
import asyncio, random, time
|
||||
|
||||
section = "Téléchargement de fichiers"
|
||||
print(f"=" * (len(section) + 4))
|
||||
print(section)
|
||||
print(f"=" * (len(section) + 4))
|
||||
|
||||
async def random_number():
|
||||
return random.uniform(1.0, 5.0)
|
||||
|
||||
async def download_file(file_id: int):
|
||||
download_time = await random_number()
|
||||
await asyncio.sleep(download_time)
|
||||
return f"fichier_{file_id}.zip", download_time
|
||||
|
||||
async def file_downloader(downloads: int = 5):
|
||||
start_time = time.perf_counter()
|
||||
tasks = []
|
||||
|
||||
for i in range(1, downloads + 1):
|
||||
task = asyncio.create_task(download_file(i))
|
||||
tasks.append(task)
|
||||
|
||||
slowest_file = None
|
||||
slowest_time = 0
|
||||
|
||||
for task in asyncio.as_completed(tasks):
|
||||
filename, download_time = await task
|
||||
print(f"{filename}: {download_time:.2f}s")
|
||||
|
||||
if download_time > slowest_time:
|
||||
slowest_time = download_time
|
||||
slowest_file = filename
|
||||
|
||||
total_time = time.perf_counter() - start_time
|
||||
print(f"\nTemps total: {total_time:.2f}s")
|
||||
print(f"Fichier le plus lent: {slowest_file} ({slowest_time:.2f}s)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(file_downloader())
|
||||
Reference in New Issue
Block a user