Skip to content

Commit

Permalink
Add asyncio example
Browse files Browse the repository at this point in the history
  • Loading branch information
everysoftware committed Nov 29, 2024
1 parent 3b03611 commit 4e86a07
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 1 deletion.
Empty file.
41 changes: 41 additions & 0 deletions src/concurrency/examples/asyncio_sleep.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import asyncio


async def compute_square(number: int) -> int:
task = asyncio.current_task()
assert task is not None
print(f"Task {task.get_name()} is processing number {number}")
await asyncio.sleep(2)
return number * number


async def sequential(numbers: list[int]) -> list[int]:
results = []
start = asyncio.get_event_loop().time()
for number in numbers:
result = await compute_square(number)
results.append(result)
finish = asyncio.get_event_loop().time()
print(f"Sequential processing time: {finish - start} seconds")
return results


async def concurrent(numbers: list[int]) -> list[int]:
start = asyncio.get_event_loop().time()
tasks = [compute_square(number) for number in numbers]
results = await asyncio.gather(*tasks)
finish = asyncio.get_event_loop().time()
print(f"Concurrent processing time: {finish - start} seconds")
return results


async def main() -> None:
numbers = [1, 2, 3, 4, 5]
print("Running sequentially:")
await sequential(numbers)
print("Running concurrently:")
await concurrent(numbers)


if __name__ == "__main__":
asyncio.run(main())
Empty file.
1 change: 0 additions & 1 deletion src/concurrency/examples/generators_sleep.py

This file was deleted.

0 comments on commit 4e86a07

Please sign in to comment.