86 lines
2.4 KiB
Python
86 lines
2.4 KiB
Python
# Exercice 1
|
|
|
|
### Appel synchrone
|
|
|
|
import time
|
|
|
|
section = "Appel Synchrone"
|
|
print(f"=" * (len(section) + 4))
|
|
print(section)
|
|
print(f"=" * (len(section) + 4))
|
|
|
|
def synchronous_fetch_users():
|
|
start = time.perf_counter()
|
|
time.sleep(2)
|
|
print(f"Users : Temps d'exécution : {time.perf_counter() - start:.2f}s")
|
|
return ["alice", "bob", "charlie"]
|
|
|
|
def synchronous_fetch_orders():
|
|
start = time.perf_counter()
|
|
time.sleep(3)
|
|
print(f"Orders : Temps d'exécution : {time.perf_counter() - start:.2f}s")
|
|
return ["order_1", "order_2"]
|
|
|
|
def synchronous_fetch_inventory():
|
|
start = time.perf_counter()
|
|
time.sleep(1)
|
|
print(f"Inventory : Temps d'exécution : {time.perf_counter() - start:.2f}s")
|
|
return ["item_A", "item_B", "item_C"]
|
|
|
|
def synchronous_main():
|
|
print(
|
|
synchronous_fetch_users(),
|
|
synchronous_fetch_orders(),
|
|
synchronous_fetch_inventory(),
|
|
)
|
|
|
|
if __name__ == "__main__":
|
|
start = time.perf_counter()
|
|
synchronous_main()
|
|
print(f"Temps total d'exécution : {time.perf_counter() - start:.2f}s")
|
|
|
|
### Appel en coroutines
|
|
|
|
import asyncio, time
|
|
|
|
section = "Appel en Co-routines"
|
|
print(f"=" * (len(section) + 4))
|
|
print(section)
|
|
print(f"=" * (len(section) + 4))
|
|
|
|
async def coro_fetch_users():
|
|
start = time.perf_counter()
|
|
await asyncio.sleep(2)
|
|
print(f"Users : Temps d'exécution : {time.perf_counter() - start:.2f}s")
|
|
return ["alice", "bob", "charlie"]
|
|
|
|
async def coro_fetch_orders():
|
|
start = time.perf_counter()
|
|
await asyncio.sleep(3)
|
|
print(f"Orders : Temps d'exécution : {time.perf_counter() - start:.2f}s")
|
|
return ["order_1", "order_2"]
|
|
|
|
async def coro_fetch_inventory():
|
|
start = time.perf_counter()
|
|
await asyncio.sleep(1)
|
|
print(f"Inventory : Temps d'exécution : {time.perf_counter() - start:.2f}s")
|
|
return ["item_A", "item_B", "item_C"]
|
|
|
|
async def coro_main():
|
|
results = await asyncio.gather(
|
|
coro_fetch_users(),
|
|
coro_fetch_orders(),
|
|
coro_fetch_inventory(),
|
|
)
|
|
return results
|
|
|
|
if __name__ == "__main__":
|
|
start = time.perf_counter()
|
|
asyncio.run(coro_main())
|
|
print(f"Temps total d'exécution : {time.perf_counter() - start:.2f}s")
|
|
|
|
conclusion = "Les tâches se sont lancées simultanément, et le temps total n'a donc pris que le temps maximal de la fonction la plus longue"
|
|
print(f"=" * len(section))
|
|
print(conclusion)
|
|
print(f"=" * len(section))
|