feat: Semaine 9
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
async => transforme une fonction en coroutine
|
||||
=> une fonction COROUTINE peut suspendre son exécution
|
||||
en cours de route et reprendre là où elle s'est
|
||||
arrêtée.
|
||||
|
||||
await => c'est le point de suspension
|
||||
=> quand une coroutine rencontre un "await", elle doit
|
||||
attendre le résultat, et signale qu'une autre
|
||||
coroutine peut se lancer en parallèle.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
# A l'ancienne
|
||||
|
||||
section = "Séquentiel"
|
||||
|
||||
print(f"{"=" * len(section)}")
|
||||
print(section)
|
||||
print(f"{"=" * len(section)}")
|
||||
|
||||
def count():
|
||||
print("One")
|
||||
time.sleep(1)
|
||||
print("Two")
|
||||
time.sleep(1)
|
||||
|
||||
def main():
|
||||
for _ in range(3):
|
||||
count()
|
||||
|
||||
if __name__ == "__main__":
|
||||
start = time.perf_counter()
|
||||
main()
|
||||
print(f"{__file__} exécuté en {time.perf_counter() - start:.2f} secondes.")
|
||||
|
||||
# Nouvelle méthode
|
||||
|
||||
section = "Asynchrone avec ASYNCIO"
|
||||
|
||||
print(f"{"=" * len(section)}")
|
||||
print(section)
|
||||
print(f"{"=" * len(section)}")
|
||||
|
||||
import asyncio
|
||||
|
||||
async def async_count():
|
||||
print("One")
|
||||
await asyncio.sleep(1)
|
||||
print("Two")
|
||||
await asyncio.sleep(1)
|
||||
|
||||
async def async_main():
|
||||
await asyncio.gather(async_count(), async_count(), async_count())
|
||||
|
||||
if __name__ == "__main__":
|
||||
start = time.perf_counter()
|
||||
asyncio.run(async_main())
|
||||
print(f"{__file__} exécuté en {time.perf_counter() - start:.2f} secondes.")
|
||||
|
||||
async def z(x):
|
||||
return x
|
||||
|
||||
async def f(x):
|
||||
y = await z(x) # si 'z' est une coroutine
|
||||
return y
|
||||
|
||||
async def g(x):
|
||||
yield x # async fonctionne sur les générateurs
|
||||
Reference in New Issue
Block a user