|
1 | | -#!/usr/env/bin python3 |
2 | | -# chained.py |
3 | | - |
4 | 1 | import asyncio |
5 | 2 | import random |
6 | 3 | import time |
7 | 4 |
|
8 | 5 |
|
9 | | -async def randint(a: int, b: int) -> int: |
10 | | - return random.randint(a, b) |
11 | | - |
| 6 | +async def main(): |
| 7 | + user_ids = [1, 2, 3] |
| 8 | + start = time.perf_counter() |
| 9 | + await asyncio.gather( |
| 10 | + *(get_user_with_posts(user_id) for user_id in user_ids) |
| 11 | + ) |
| 12 | + end = time.perf_counter() |
| 13 | + print(f"\n==> Total time: {end - start:.2f} seconds") |
12 | 14 |
|
13 | | -async def part1(n: int) -> str: |
14 | | - i = await randint(0, 10) |
15 | | - print(f"part1({n}) sleeping for {i} seconds.") |
16 | | - await asyncio.sleep(i) |
17 | | - result = f"result{n}-1" |
18 | | - print(f"Returning part1({n}) == {result}.") |
19 | | - return result |
20 | 15 |
|
| 16 | +async def get_user_with_posts(user_id): |
| 17 | + user = await fetch_user(user_id) |
| 18 | + await fetch_posts(user) |
21 | 19 |
|
22 | | -async def part2(n: int, arg: str) -> str: |
23 | | - i = await randint(0, 10) |
24 | | - print(f"part2{n, arg} sleeping for {i} seconds.") |
25 | | - await asyncio.sleep(i) |
26 | | - result = f"result{n}-2 derived from {arg}" |
27 | | - print(f"Returning part2{n, arg} == {result}.") |
28 | | - return result |
29 | 20 |
|
| 21 | +async def fetch_user(user_id): |
| 22 | + delay = random.uniform(0.5, 2.0) |
| 23 | + print(f"User coro: fetching user by {user_id=}...") |
| 24 | + await asyncio.sleep(delay) |
| 25 | + user = {"id": user_id, "name": f"User{user_id}"} |
| 26 | + print(f"User coro: fetched user with {user_id=} (done in {delay:.1f}s).") |
| 27 | + return user |
30 | 28 |
|
31 | | -async def chain(n: int) -> None: |
32 | | - start = time.perf_counter() |
33 | | - p1 = await part1(n) |
34 | | - p2 = await part2(n, p1) |
35 | | - end = time.perf_counter() - start |
36 | | - print(f"-->Chained result{n} => {p2} (took {end:0.2f} seconds).") |
37 | 29 |
|
38 | | - |
39 | | -async def main(*args): |
40 | | - await asyncio.gather(*(chain(n) for n in args)) |
| 30 | +async def fetch_posts(user): |
| 31 | + delay = random.uniform(0.5, 2.0) |
| 32 | + print(f"Post coro: retrieving posts for {user['name']}...") |
| 33 | + await asyncio.sleep(delay) |
| 34 | + posts = [f"Post {i} by {user['name']}" for i in range(1, 3)] |
| 35 | + print( |
| 36 | + f"Post coro: got {len(posts)} posts by {user['name']}" |
| 37 | + f" (done in {delay:.1f}s):" |
| 38 | + ) |
| 39 | + for post in posts: |
| 40 | + print(f" - {post}") |
41 | 41 |
|
42 | 42 |
|
43 | 43 | if __name__ == "__main__": |
44 | | - import sys |
45 | | - |
46 | 44 | random.seed(444) |
47 | | - args = [1, 2, 3] if len(sys.argv) == 1 else map(int, sys.argv[1:]) |
48 | | - start = time.perf_counter() |
49 | | - asyncio.run(main(*args)) |
50 | | - end = time.perf_counter() - start |
51 | | - print(f"Program finished in {end:0.2f} seconds.") |
| 45 | + asyncio.run(main()) |
0 commit comments