15. Performance and concurrency — Exercises
These exercises practice every idea of the Performance and concurrency lesson. They use the course datasets: data/sales.csv, data/customers.csv, data/products.csv, data/stores.csv, data/sensors.csv, the monthly files in data/reports/ and the API fixtures in data/api/.
How to work:
- Copy the setup block below to the top of a script, for example
exercise.py. - Add the starter code of an exercise and replace each to-do comment with your code.
- Run the script with
python exercise.pyand compare your output with the expected output. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Timings differ between machines, so no solution prints a duration. The solutions print comparisons such as max() is faster: True, counts of operations and call counts instead. Each comparison has a wide safety margin, so it holds on a slow laptop too.
import asyncioimport csvimport timeimport timeitfrom collections import Counter, defaultdict, dequefrom concurrent.futures import ThreadPoolExecutor, as_completed
def load_csv(path: str) -> list[dict[str, str]]: """Read a CSV file into a list of dicts, one dict per row.""" with open(path, newline="", encoding="utf-8") as f: return list(csv.DictReader(f))Warm-up
Section titled “Warm-up”M15-W01 · Count loop steps to find the big-O
Section titled “M15-W01 · Count loop steps to find the big-O”Three helpers of a sensor pipeline have three loop shapes: one pass over the readings, a comparison of every reading with every reading, and a search that halves its range until one item is left. Write each loop so that it returns the number of steps it makes for n readings. Print a table for n = 10, 100 and 1,000. Then name the big-O class of each loop.
n one_pass all_pairs halving 10 10 100 3 100 100 10,000 6 1,000 1,000 1,000,000 9def one_pass(n: int) -> int: steps = 0 # TODO: one step per reading return steps
def all_pairs(n: int) -> int: steps = 0 # TODO: one step for every pair (i, j) of readings return steps
def halving(n: int) -> int: steps = 0 # TODO: halve n with // 2 until it is 1, one step per halving return steps
# TODO: print the header and one row per nHint 1
one_pass is a single for _ in range(n): loop. all_pairs has a second loop inside the first.
Hint 2
halving is a while n > 1: loop with n //= 2 and steps += 1 inside. Format the table with f"{n:>6} {one_pass(n):>8,}" and so on.
Solution
def one_pass(n: int) -> int: steps = 0 for _ in range(n): steps += 1 return steps
def all_pairs(n: int) -> int: steps = 0 for _ in range(n): for _ in range(n): steps += 1 return steps
def halving(n: int) -> int: steps = 0 while n > 1: n //= 2 steps += 1 return steps
print(f"{'n':>6} {'one_pass':>8} {'all_pairs':>10} {'halving':>8}")for n in (10, 100, 1_000): print(f"{n:>6,} {one_pass(n):>8,} {all_pairs(n):>10,} {halving(n):>8}")assert all_pairs(1_000) == one_pass(1_000) ** 2assert halving(1_024) == 10 n one_pass all_pairs halving 10 10 100 3 100 100 10,000 6 1,000 1,000 1,000,000 9How it works:
one_passgrows by 10 whenngrows by 10: linear, .all_pairsgrows by 100 whenngrows by 10: quadratic, . 1,000 readings already cost a million steps.halvinggrows by about 3 whenngrows by 10: logarithmic, . It counts how often you can halven, which is .
Alternative: compute the counts without loops: n, n * n and n.bit_length() - 1 give the same three numbers. The loops are there to show where the counts come from.
M15-W02 · Find the largest order without sorting
Section titled “M15-W02 · Find the largest order without sorting”A dashboard shows the largest line revenue of data/sales.csv. The current code sorts all revenues and takes the last one. Write the same with max(), check that both give the same answer and use timeit (50 runs each) to show which is faster.
Largest line revenue: 5196.0Same answer: Truemax() is faster: Truerevenues = [float(row["revenue"]) for row in load_csv("data/sales.csv")]largest_by_sort = sorted(revenues)[-1]# TODO: the same value with max()# TODO: time both with timeit.timeit(..., number=50)# TODO: print the value, "Same answer:" and "max() is faster:"Hint 1
max() looks at each value once: . Sorting is and builds a new list.
Hint 2
timeit.timeit(lambda: max(revenues), number=50) returns the total time of 50 calls in seconds. Compare the two totals with <.
Solution
revenues = [float(row["revenue"]) for row in load_csv("data/sales.csv")]largest_by_sort = sorted(revenues)[-1]largest = max(revenues)
sort_s = timeit.timeit(lambda: sorted(revenues)[-1], number=50)max_s = timeit.timeit(lambda: max(revenues), number=50)print("Largest line revenue:", largest)print("Same answer:", largest == largest_by_sort)print("max() is faster:", max_s < sort_s)assert largest == largest_by_sortassert max_s < sort_sLargest line revenue: 5196.0Same answer: Truemax() is faster: TrueHow it works:
sorted()builds and sorts a copy of all 20,228 values, only to keep one.max()keeps the largest value seen so far in one pass and builds nothing.- Both
timeitcalls run 50 times, so the totals are directly comparable.
Alternative: for the top 10 instead of the top 1, use heapq.nlargest(10, revenues). It keeps only 10 values while it scans.
M15-W03 · Tell I/O-bound from CPU-bound work
Section titled “M15-W03 · Tell I/O-bound from CPU-bound work”Write classify(task). It runs task(), measures its wall-clock time with time.perf_counter() and its CPU time with time.process_time(), and returns "I/O-bound" when the CPU time is less than half the wall time, else "CPU-bound". Classify the two tasks in the starter.
simulated_query: I/O-boundscore_customers: CPU-bounddef simulated_query() -> int: time.sleep(0.2) # waits for a database server return 5_000
def score_customers() -> float: rows = load_csv("data/customers.csv") total = 0.0 for _ in range(20): for row in rows: total += float(row["monthly_charges"]) * int(row["support_tickets"]) return total
def classify(task) -> str: # TODO: measure wall and CPU time around task() # TODO: return "I/O-bound" or "CPU-bound" ...
# TODO: print one line per taskHint 1
Take both clocks before the call and both after: wall_start, cpu_start = time.perf_counter(), time.process_time().
Hint 2
time.sleep() costs wall time but almost no CPU time. A loop that computes costs both. Print with f"{task.__name__}: {classify(task)}".
Solution
from collections.abc import Callable
def simulated_query() -> int: time.sleep(0.2) # waits for a database server return 5_000
def score_customers() -> float: rows = load_csv("data/customers.csv") total = 0.0 for _ in range(20): for row in rows: total += float(row["monthly_charges"]) * int(row["support_tickets"]) return total
def classify(task: Callable[[], object]) -> str: wall_start, cpu_start = time.perf_counter(), time.process_time() task() wall = time.perf_counter() - wall_start cpu = time.process_time() - cpu_start return "I/O-bound" if cpu < wall / 2 else "CPU-bound"
results = {task.__name__: classify(task) for task in (simulated_query, score_customers)}for name, kind in results.items(): print(f"{name}: {kind}")assert results == {"simulated_query": "I/O-bound", "score_customers": "CPU-bound"}simulated_query: I/O-boundscore_customers: CPU-boundHow it works:
perf_counter()measures the time on the clock: waiting counts.process_time()measures only the time the CPU spent on this process: waiting does not count.simulated_querywaits 0.2 s and uses almost no CPU, so its ratio is near 0.score_customerscomputes the whole time, so its ratio is near 1.- The type hint
Callable[[], object]means “a function that takes no arguments” (module 12).
Alternative: in a real program, watch a system monitor (Activity Monitor, Task Manager or top) while the code runs. A CPU-bound Python process shows about 100% of one core. An I/O-bound one shows almost 0%.
M15-W04 · Predict the output: map order and finish order
Section titled “M15-W04 · Predict the output: map order and finish order”Predict the output: read the code and write down the two lines it prints. slow_double(n) waits n / 10 seconds before it returns.
Acceptance criteria:
- Write your prediction line by line, then run the code.
- Your prediction matches the Output in the solution, including the order of the numbers.
def slow_double(n: int) -> int: time.sleep(n / 10) return 2 * n
with ThreadPoolExecutor(max_workers=3) as pool: print(list(pool.map(slow_double, [3, 1, 2]))) futures = [pool.submit(slow_double, n) for n in [3, 1, 2]] print([future.result() for future in as_completed(futures)])Hint 1
All three tasks run at the same time on 3 threads. Which one finishes first?
Hint 2
map() returns results in the order of its input. as_completed() yields futures in the order they finish.
Solution
def slow_double(n: int) -> int: time.sleep(n / 10) return 2 * n
with ThreadPoolExecutor(max_workers=3) as pool: by_input = list(pool.map(slow_double, [3, 1, 2])) print(by_input) futures = [pool.submit(slow_double, n) for n in [3, 1, 2]] by_finish = [future.result() for future in as_completed(futures)] print(by_finish)assert by_input == [6, 2, 4]assert by_finish == sorted(by_finish)[6, 2, 4][2, 4, 6]How it works:
map()starts all three tasks, then yields the results in input order: the result for 3, then 1, then 2. It waits for the slow first task before it gives you anything.as_completed()yields each future as soon as it is done. The task for 1 waits 0.1 s, so its result 2 comes first, then 4, then 6.- The order of
as_completeddepends on timing. Here the waits differ by 0.1 s, which is long enough to make the order reliable. With equal waits it would change from run to run.
Alternative: to get finish order and know which input each result belongs to, keep a dict {future: n} and look up futures[future] in the loop.
M15-W05 · Find unknown customer IDs with a set
Section titled “M15-W05 · Find unknown customer IDs with a set”data/sales_raw.csv is a messy export with 1,200 lines. Some lines have a customer_id that is not a real customer. Build a set of the IDs in data/customers.csv and count the lines of sales_raw.csv whose customer_id is not in it. Print the count and the distinct unknown values, sorted.
Lines with an unknown customer: 23Distinct unknown values: ['', '-', 'N/A']customers = load_csv("data/customers.csv")raw = load_csv("data/sales_raw.csv")# TODO: a set of known customer IDs# TODO: the customer_id of every raw line that is not known# TODO: print the count and the sorted distinct valuesHint 1
A set comprehension builds the set: {row["customer_id"] for row in customers}.
Hint 2
not in on a set is one hash lookup. Use sorted(set(unknown)) for a stable display.
Solution
customers = load_csv("data/customers.csv")raw = load_csv("data/sales_raw.csv")known = {row["customer_id"] for row in customers}unknown = [row["customer_id"] for row in raw if row["customer_id"] not in known]print("Lines with an unknown customer:", len(unknown))print("Distinct unknown values:", sorted(set(unknown)))assert len(known) == 5_000assert len(unknown) == 23Lines with an unknown customer: 23Distinct unknown values: ['', '-', 'N/A']How it works:
- The set holds 5,000 IDs. Each
not intest costs one hash lookup, so the whole check is . - The 23 unknown values are the three missing-value tokens of the raw export: the empty string,
-andN/A. Module 26 cleans them. sorted(set(...))gives a fixed order. Printing a set of strings directly can show a different order on every run.
Alternative: set algebra gives the distinct unknown values in one line: sorted({row["customer_id"] for row in raw} - known). It does not count the lines, though.
M15-W06 · Keep a rolling window with deque
Section titled “M15-W06 · Keep a rolling window with deque”Sensor S1’s temperatures are in data/sensors.csv, one every 10 minutes. Keep the last 6 valid readings (about one hour) in a deque(maxlen=6) with a running sum. Count the full windows whose mean is above 25.0 °C and print the timestamp of the first one. Skip blank readings.
Hot windows: 12First hot window ends at: 2024-05-02T12:30:00rows = [r for r in load_csv("data/sensors.csv") if r["sensor_id"] == "S1"]window: deque[float] = deque(maxlen=6)running_sum = 0.0hot_windows = 0first_hot = Nonefor row in rows: # TODO: skip blank temperatures # TODO: update running_sum before the deque drops its oldest value # TODO: count full windows with a mean above 25.0 and keep the first timestamp ...# TODO: print the two resultsHint 1
When the deque is full, append() drops window[0]. Subtract it from the running sum first.
Hint 2
if len(window) == window.maxlen: running_sum -= window[0]window.append(value)running_sum += valueSolution
rows = [r for r in load_csv("data/sensors.csv") if r["sensor_id"] == "S1"]window: deque[float] = deque(maxlen=6)running_sum = 0.0hot_windows = 0first_hot = Nonefor row in rows: if not row["temperature_c"]: continue value = float(row["temperature_c"]) if len(window) == window.maxlen: running_sum -= window[0] # the value that append() will drop window.append(value) running_sum += value if len(window) == window.maxlen and running_sum / window.maxlen > 25.0: hot_windows += 1 if first_hot is None: first_hot = row["timestamp"]print("Hot windows:", hot_windows)print("First hot window ends at:", first_hot)assert hot_windows > 0assert first_hot is not None and first_hot.startswith("2024-05")Hot windows: 12First hot window ends at: 2024-05-02T12:30:00How it works:
deque(maxlen=6)keeps at most 6 items.append()on a full deque drops the oldest one in .- The running sum changes by two values per reading, so each mean costs instead of
sum(window)over 6 values. With a window of 1,000 readings, this is the difference between 1,000 additions and 2. - Floats collect tiny rounding errors in a long running sum. For millions of values, recompute the sum from the deque now and then, or use NumPy (module 23).
Alternative: sum(window) / len(window) in each step is simpler and fine for a window of 6. Choose the running sum when the window is large.
M15-W07 · Fix the bug: the coroutines never run
Section titled “M15-W07 · Fix the bug: the coroutines never run”Fix the bug: this code should fetch the average ratings of P001, P002 and P003 concurrently. It prints a list of coroutine objects and a “never awaited” warning instead. The ratings come from data/api/products_page_1.json. Fix it so that it prints the three ratings, fetched concurrently.
[3.8, 3.9, 4.0]import json
with open("data/api/products_page_1.json", encoding="utf-8") as f: RATINGS = {item["id"]: item["rating"]["average"] for item in json.load(f)["data"]}
async def fetch_rating(product_id: str) -> float: await asyncio.sleep(0.1) # a simulated API call return RATINGS[product_id]
async def main() -> list[float]: results = [] for product_id in ["P001", "P002", "P003"]: results.append(fetch_rating(product_id)) # bug return results
print(asyncio.run(main()))Hint 1
Calling a coroutine function only creates a coroutine. Something must await it.
Hint 2
await asyncio.gather(*coroutines) runs them all at once and returns their results in order.
Solution
import json
with open("data/api/products_page_1.json", encoding="utf-8") as f: RATINGS = {item["id"]: item["rating"]["average"] for item in json.load(f)["data"]}
async def fetch_rating(product_id: str) -> float: await asyncio.sleep(0.1) # a simulated API call return RATINGS[product_id]
async def main() -> list[float]: ids = ["P001", "P002", "P003"] return await asyncio.gather(*(fetch_rating(pid) for pid in ids))
start = time.perf_counter()ratings = asyncio.run(main())elapsed = time.perf_counter() - startprint(ratings)assert ratings == [RATINGS["P001"], RATINGS["P002"], RATINGS["P003"]]assert elapsed < 0.25 # concurrent: about 0.1 s, not 0.3 s[3.8, 3.9, 4.0]How it works:
fetch_rating(product_id)returns a coroutine object. The buggy loop collected three of them and never ran them.asyncio.gather(*...)schedules all three on the event loop. They wait at the same time, so the run takes about 0.1 s.- The results come back in the order of the arguments, whatever the finish order.
Alternative: results.append(await fetch_rating(product_id)) inside the loop also fixes the bug, but it runs the calls one after another: 0.3 s instead of 0.1 s. It is correct, and slow.
M15-W08 · Query three data sources at once
Section titled “M15-W08 · Query three data sources at once”A morning report needs three counts from three systems: the sales database (answers in 0.3 s), the CRM (0.2 s) and the inventory system (0.1 s). Simulate each system with a coroutine that waits with asyncio.sleep() and then counts the rows of its CSV file. Run the three at once with asyncio.gather() and print the counts. The whole run must take less than 0.45 s.
sales 20,228 rowscrm 5,000 rowsinventory 30 rowsasync def count_rows(system: str, path: str, delay: float) -> tuple[str, int]: # TODO: wait `delay` seconds, then return the system name and the row count ...
async def main() -> list[tuple[str, int]]: # TODO: gather the three systems ...
# TODO: run main(), time it, print one line per systemHint 1
await asyncio.sleep(delay) waits without blocking the other coroutines. len(load_csv(path)) counts the rows.
Hint 2
asyncio.gather(count_rows("sales", "data/sales.csv", 0.3), ...) returns the three tuples in argument order.
Solution
async def count_rows(system: str, path: str, delay: float) -> tuple[str, int]: await asyncio.sleep(delay) # the system takes this long to answer return system, len(load_csv(path))
async def main() -> list[tuple[str, int]]: return await asyncio.gather( count_rows("sales", "data/sales.csv", 0.3), count_rows("crm", "data/customers.csv", 0.2), count_rows("inventory", "data/products.csv", 0.1), )
start = time.perf_counter()counts = asyncio.run(main())elapsed = time.perf_counter() - startfor system, rows in counts: print(f"{system:<10} {rows:>6,} rows")assert dict(counts) == {"sales": 20_228, "crm": 5_000, "inventory": 30}assert elapsed < 0.45sales 20,228 rowscrm 5,000 rowsinventory 30 rowsHow it works:
- The three coroutines start together. Their waits overlap, so the run takes about 0.3 s, the longest wait, plus the time to read the files.
load_csvis ordinary blocking code, but it is fast. Only the waits need to be async.gatherkeeps the order of its arguments, sosalescomes first although it answers last.
Alternative: with asyncio.TaskGroup (Python 3.11+), create three tasks inside async with asyncio.TaskGroup() as tg: and read task.result() after the block. If one task fails, the group cancels the others.
M15-W09 · Refactor: count categories in one pass
Section titled “M15-W09 · Refactor: count categories in one pass”Refactor: the starter counts the sales lines per category with list.count(), which scans the whole list once per category. Rewrite it with collections.Counter, which needs one pass. Print the counts from most to least common, the number of items each version reads, and check that both versions agree.
Clothing 4,014Electronics 3,942Sports 3,331Home 3,265Beauty 3,109Books 2,567Items read: 121,368 vs 20,228Same counts: Truecategories = [row["category"] for row in load_csv("data/sales.csv")]slow = {category: categories.count(category) for category in sorted(set(categories))}# TODO: the same counts with Counter# TODO: print the counts, most common first# TODO: print how many items each version reads, and "Same counts:"Hint 1
Counter(categories) counts everything in one pass. .most_common() returns (category, count) pairs, largest first.
Hint 2
The slow version calls count() once per category, and each call reads all lines: len(set(categories)) * len(categories) items.
Solution
categories = [row["category"] for row in load_csv("data/sales.csv")]slow = {category: categories.count(category) for category in sorted(set(categories))}fast = Counter(categories)for category, lines in fast.most_common(): print(f"{category:<12} {lines:>5,}")print(f"Items read: {len(slow) * len(categories):,} vs {len(categories):,}")print("Same counts:", slow == fast)assert slow == fastassert fast.most_common(1) == [("Clothing", 4_014)]Clothing 4,014Electronics 3,942Sports 3,331Home 3,265Beauty 3,109Books 2,567Items read: 121,368 vs 20,228Same counts: TrueHow it works:
categories.count(c)is , and the comprehension calls it once per category: forkcategories.Counterupdates one dict entry per line: , whatever the number of categories.- With 6 categories the slow version reads 6 times more items. With 5,000 customer IDs instead of 6 categories, it would read 5,000 times more.
Counteris a dict subclass, soslow == fastcompares the counts directly.
Alternative: defaultdict(int) with counts[category] += 1 in a loop is also one pass. Counter is shorter and adds most_common().
M15-C01 · Cache a slow lookup and prove it with cProfile
Section titled “M15-C01 · Cache a slow lookup and prove it with cProfile”category_of() in the starter reads data/products.csv from disk every time it is called. Profile count_categories() on the first 1,000 sales lines and print the call counts of category_of and load_csv. Then add functools.cache to category_of, profile again and print the new counts. Check that the result did not change.
Without cache: {'category_of': '1000', 'load_csv': '1000'}With cache: {'category_of': '26', 'load_csv': '26'}Same result: Trueimport cProfileimport pstats
def category_of(product_id: str) -> str: for row in load_csv("data/products.csv"): # reads the file on every call if row["product_id"] == product_id: return row["category"] raise KeyError(product_id)
def count_categories(lines: list[dict[str, str]]) -> Counter[str]: return Counter(category_of(line["product_id"]) for line in lines)
lines = load_csv("data/sales.csv")[:1_000]# TODO: a function that profiles count_categories(lines) and returns the result# and the ncalls of category_of and load_csv# TODO: profile, add functools.cache, profile again, print bothHint 1
pstats.Stats(profiler).get_stats_profile().func_profiles is a dict from function name to an object with an ncalls attribute.
Hint 2
functools.cache(category_of) returns a cached version. Assign it back to the same name, so count_categories uses it: category_of = functools.cache(category_of).
Solution
import cProfileimport functoolsimport pstats
def category_of(product_id: str) -> str: for row in load_csv("data/products.csv"): # reads the file on every call if row["product_id"] == product_id: return row["category"] raise KeyError(product_id)
def count_categories(lines: list[dict[str, str]]) -> Counter[str]: return Counter(category_of(line["product_id"]) for line in lines)
def profile_counts(lines: list[dict[str, str]]) -> tuple[Counter[str], dict[str, str]]: with cProfile.Profile() as profiler: result = count_categories(lines) funcs = pstats.Stats(profiler).get_stats_profile().func_profiles calls = {name: funcs[name].ncalls for name in ("category_of", "load_csv")} return result, calls
lines = load_csv("data/sales.csv")[:1_000]before, calls_before = profile_counts(lines)category_of = functools.cache(category_of) # count_categories now uses the cacheafter, calls_after = profile_counts(lines)print("Without cache:", calls_before)print("With cache: ", calls_after)print("Same result:", before == after)assert calls_before == {"category_of": "1000", "load_csv": "1000"}assert int(calls_after["load_csv"]) <= 30assert before == afterWithout cache: {'category_of': '1000', 'load_csv': '1000'}With cache: {'category_of': '26', 'load_csv': '26'}Same result: TrueHow it works:
- Without the cache, every line opens and parses the products file: 1,000 file reads for 1,000 lines. The profile makes the waste visible in one number.
functools.cachestores each result by its argument. The real function runs once per distinct product ID: 26 of the 30 products appear in the first 1,000 lines. The other 974 calls are dict lookups inside the cache, and the profiler does not even count them as calls ofcategory_of.ncallsis a string inFunctionProfile, because recursive functions show values such as"3/1".
Alternative: load the file once and build a dict, as in the lesson: category = {r["product_id"]: r["category"] for r in load_csv("data/products.csv")}. This is clearer when you control the code. A cache is the quick fix for a function you cannot change.
M15-C02 · Revenue by city with a dict index
Section titled “M15-C02 · Revenue by city with a dict index”data/sales.csv has a store_id but no city. The city is in data/stores.csv. Build a dict index from store_id to city, compute the revenue per city in one pass over the sales lines and print the three cities with the most revenue. Check that the city totals add up to the total revenue.
New York 468,290.16Chicago 406,532.46Seattle 401,382.78Cities add up: Truestores = load_csv("data/stores.csv")sales = load_csv("data/sales.csv")# TODO: city_of = {...}# TODO: revenue per city in one pass# TODO: print the top 3, largest first, and check the totalHint 1
city_of = {s["store_id"]: s["city"] for s in stores}. Then city_of[line["store_id"]] is an lookup.
Hint 2
Sort the (city, revenue) pairs with key=lambda item: item[1], reverse=True and take [:3]. Compare floats with math.isclose().
Solution
import math
stores = load_csv("data/stores.csv")sales = load_csv("data/sales.csv")city_of = {store["store_id"]: store["city"] for store in stores}revenue_by_city: dict[str, float] = defaultdict(float)for line in sales: revenue_by_city[city_of[line["store_id"]]] += float(line["revenue"])
top = sorted(revenue_by_city.items(), key=lambda item: item[1], reverse=True)[:3]for city, revenue in top: print(f"{city:<10} {revenue:>12,.2f}")total = sum(float(line["revenue"]) for line in sales)print("Cities add up:", math.isclose(sum(revenue_by_city.values()), total))assert len(city_of) == 12assert top[0][0] == "New York"New York 468,290.16Chicago 406,532.46Seattle 401,382.78Cities add up: TrueHow it works:
- The index has 12 entries and takes one pass over
storesto build. - The main loop does one dict lookup and one addition per line: in total.
- New York (S07) leads. The store sizes in
data/stores.csvexplain it: S07 is the largest store (3,400 m²), and sales volume grows with floor area. math.isclosecompares the two float sums, which were added in different orders.
Alternative: heapq.nlargest(3, revenue_by_city.items(), key=lambda item: item[1]) returns the top 3 without sorting all 12 cities. For 12 items, either is fine.
M15-C03 · Interpret a profile: a function called too often
Section titled “M15-C03 · Interpret a profile: a function called too often”Interpret a result: the starter matches 2,000 sales lines to products by their name, after cleaning each name with normalize(). Profile match_products() and print the call counts of your two functions. Explain the number of normalize calls: how many calls per sales line, and why? Then fix the code so that normalize runs once per product and once per line, and profile again.
Slow: {'match_products': 1, 'normalize': 59288}normalize calls per line: 29.6Fast: {'match_products_fast': 1, 'normalize': 2030}Same matches: Trueimport cProfileimport pstatsfrom collections.abc import Callable
products = load_csv("data/products.csv")lines = load_csv("data/sales.csv")[:2_000]
def normalize(name: str) -> str: return " ".join(name.lower().split())
def match_products(lines: list[dict[str, str]]) -> int: matched = 0 for line in lines: for product in products: if normalize(product["product"]) == normalize(line["product"]): matched += 1 break return matched
# TODO: profile match_products(lines), print ncalls of normalize and match_products# TODO: write match_products_fast with a dict of normalized names, profile it tooHint 1
Collect ncalls from pstats.Stats(profiler).get_stats_profile().func_profiles for the function names you care about. Divide the normalize count by the number of lines.
Hint 2
The inner loop normalizes both names for every product it tries. Normalize the 30 product names once into a dict {normalized_name: product_id}, then normalize each line once and look it up.
Solution
import cProfileimport pstatsfrom collections.abc import Callable
products = load_csv("data/products.csv")lines = load_csv("data/sales.csv")[:2_000]
def normalize(name: str) -> str: return " ".join(name.lower().split())
def match_products(lines: list[dict[str, str]]) -> int: matched = 0 for line in lines: for product in products: if normalize(product["product"]) == normalize(line["product"]): matched += 1 break return matched
def match_products_fast(lines: list[dict[str, str]]) -> int: known = {normalize(p["product"]): p["product_id"] for p in products} # 30 calls return sum(normalize(line["product"]) in known for line in lines) # 1 per line
def calls( func: Callable[[list[dict[str, str]]], int], names: tuple[str, ...]) -> tuple[int, dict[str, int]]: with cProfile.Profile() as profiler: result = func(lines) funcs = pstats.Stats(profiler).get_stats_profile().func_profiles return result, {name: int(funcs[name].ncalls) for name in names}
slow_result, slow_calls = calls(match_products, ("match_products", "normalize"))fast_names = ("match_products_fast", "normalize")fast_result, fast_calls = calls(match_products_fast, fast_names)print("Slow:", slow_calls)print(f"normalize calls per line: {slow_calls['normalize'] / len(lines):.1f}")print("Fast:", fast_calls)print("Same matches:", slow_result == fast_result == len(lines))assert fast_calls["normalize"] == len(products) + len(lines)Slow: {'match_products': 1, 'normalize': 59288}normalize calls per line: 29.6Fast: {'match_products_fast': 1, 'normalize': 2030}Same matches: TrueHow it works:
- Interpretation.
normalizeruns about 30 times per line. For each line, the inner loop tries products until it finds the match, about 15 of the 30 products on average, and each try normalizes two names. Product names are normalized again and again, although they never change. A call count that is a multiple of the row count is the sign of work inside an inner loop. - Fix. Normalize the 30 product names once into a dict. Then each line costs one
normalizeand one lookup: 2,030 calls instead of 59,288. - Both versions match all 2,000 lines, so the fix changed the speed and not the answer.
Alternative: if you need the matched product for each line, keep the dict and write known.get(normalize(line["product"])), which returns None for an unknown name.
M15-C04 · Download the catalog pages with a thread pool
Section titled “M15-C04 · Download the catalog pages with a thread pool”The product API returns 3 pages (data/api/products_page_1.json to _3.json). Each request waits 0.2 s for the network. Write fetch_page(page) that waits and returns the page’s JSON. Fetch the three pages with a ThreadPoolExecutor, keep the page order, and print the number of products, the IDs that are out of stock (stock is 0) and whether the whole fetch took less than 0.45 s.
Products: 30Out of stock: ['P006', 'P019']Under 0.45 s: Trueimport jsonfrom typing import Any
def fetch_page(page: int) -> dict[str, Any]: # TODO: sleep 0.2 s, then read and return data/api/products_page_{page}.json ...
# TODO: fetch pages 1, 2 and 3 with ThreadPoolExecutor and pool.map# TODO: collect all products in page order and print the three resultsHint 1
pool.map(fetch_page, [1, 2, 3]) returns the three page dicts in page order.
Hint 2
Each page dict has a "data" list. Flatten with a nested comprehension: [item for page in pages for item in page["data"]].
Solution
import jsonfrom typing import Any
def fetch_page(page: int) -> dict[str, Any]: time.sleep(0.2) # simulated network latency with open(f"data/api/products_page_{page}.json", encoding="utf-8") as f: return json.load(f)
start = time.perf_counter()with ThreadPoolExecutor(max_workers=3) as pool: pages = list(pool.map(fetch_page, [1, 2, 3]))elapsed = time.perf_counter() - start
products = [item for page in pages for item in page["data"]]out_of_stock = [item["id"] for item in products if item["stock"] == 0]print("Products:", len(products))print("Out of stock:", out_of_stock)print("Under 0.45 s:", elapsed < 0.45)assert [page["page"] for page in pages] == [1, 2, 3]assert products[0]["id"] == "P001" and products[-1]["id"] == "P030"Products: 30Out of stock: ['P006', 'P019']Under 0.45 s: TrueHow it works:
- Three threads wait for their pages at the same time, so the fetch takes about 0.2 s instead of 0.6 s.
pool.mapkeeps the page order, so the products come out as P001 to P030.- The check
elapsed < 0.45has a wide margin: it fails only if the pages were fetched one after another.
Alternative: real paginated APIs often do not tell you the number of pages in advance. Then you must follow the next links one page at a time, and threads cannot help. Module 16 handles that case. When the total is known, as here (total_pages: 3), fetch all pages at once.
M15-C05 · Collect errors from futures
Section titled “M15-C05 · Collect errors from futures”A script asks for pages 1 to 5 of the product API, but only 3 pages exist. Fetch all five with submit() and as_completed(). Collect the good pages and the failed page numbers, so that one missing page does not stop the others. Print both lists sorted and the number of products loaded.
Loaded pages: [1, 2, 3]Failed pages: [4, 5]Products: 30import jsonfrom typing import Any
def fetch_page(page: int) -> list[dict[str, Any]]: time.sleep(0.1) with open(f"data/api/products_page_{page}.json", encoding="utf-8") as f: return json.load(f)["data"]
loaded: dict[int, list[dict[str, Any]]] = {}failed: list[int] = []# TODO: submit pages 1-5, map each future to its page number# TODO: in as_completed, store good results in loaded and page numbers in failed# TODO: print the sorted loaded pages, the sorted failed pages and the product countHint 1
futures = {pool.submit(fetch_page, page): page for page in range(1, 6)} remembers which page each future belongs to.
Hint 2
Wrap future.result() in try / except FileNotFoundError. The exception from the worker thread is raised again at result().
Solution
import jsonfrom typing import Any
def fetch_page(page: int) -> list[dict[str, Any]]: time.sleep(0.1) with open(f"data/api/products_page_{page}.json", encoding="utf-8") as f: return json.load(f)["data"]
loaded: dict[int, list[dict[str, Any]]] = {}failed: list[int] = []with ThreadPoolExecutor(max_workers=5) as pool: futures = {pool.submit(fetch_page, page): page for page in range(1, 6)} for future in as_completed(futures): page = futures[future] try: loaded[page] = future.result() except FileNotFoundError: failed.append(page)
print("Loaded pages:", sorted(loaded))print("Failed pages:", sorted(failed))print("Products:", sum(len(items) for items in loaded.values()))assert sorted(failed) == [4, 5]Loaded pages: [1, 2, 3]Failed pages: [4, 5]Products: 30How it works:
- Pages 4 and 5 raise
FileNotFoundErrorinside their threads. The executor catches the exception and stores it in the future. future.result()raises it again in the main thread, where thetryblock handles it per page.as_completedyields in finish order, which can change between runs.sorted()makes the output fixed.- With
pool.map(), the first failure would raise inside the loop and you would lose the results that come after it.
Alternative: future.exception() returns the exception (or None) without raising it. if (error := future.exception()) is None: avoids the try block.
M15-C06 · Choose the right tool and justify it
Section titled “M15-C06 · Choose the right tool and justify it”Choose a method and justify it: for each scenario, choose "threads", "processes", "asyncio" or "vectorize" (NumPy or pandas, no concurrency). Store your choices in a dict, print one line per scenario with a short reason and check your choices with asserts.
- Download 300 daily CSV exports from an internal web server with the
requestslibrary. - Compute 10,000 bootstrap resamples of a custom pure Python statistic for each of 8 regions.
- A chat service keeps 2,000 open connections that mostly wait for messages; it uses an async web framework.
- Standardize a numeric column of 5 million floats: subtract the mean, divide by the standard deviation.
- An async web app must call a partner API that allows at most 5 parallel requests.
Acceptance criteria:
- One choice per scenario, each with a reason of one line.
- The choices match the solution, and your reasons name the deciding fact: waiting or computing, async library or not.
choices = { "download 300 CSV exports": ..., # TODO "bootstrap 8 regions": ..., # TODO "2,000 chat connections": ..., # TODO "standardize 5 million floats": ..., # TODO "partner API, max 5 parallel": ..., # TODO}# TODO: print each scenario, the choice and a reasonHint 1
First ask: is the slow part waiting (I/O-bound) or computing (CPU-bound)? Then ask: is there an async library, or a vectorized library?
Hint 2
requests is blocking: it cannot run inside asyncio without a thread. A pure Python statistic cannot be vectorized easily and is held back by the GIL in threads.
Solution
choices = { "download 300 CSV exports": ( "threads", "I/O-bound; a waiting thread releases the GIL", ), "bootstrap 8 regions": ( "processes", "CPU-bound pure Python; one GIL per process", ), "2,000 chat connections": ( "asyncio", "thousands of waiting tasks, one thread", ), "standardize 5 million floats": ( "vectorize", "NumPy runs the math in C", ), "partner API, max 5 parallel": ( "asyncio", "async app; Semaphore(5) keeps the limit", ),}for scenario, (tool, reason) in choices.items(): print(f"{scenario:<30} {tool:<10} {reason}")tools = [tool for tool, _ in choices.values()]assert tools == ["threads", "processes", "asyncio", "vectorize", "asyncio"]download 300 CSV exports threads I/O-bound; a waiting thread releases the GILbootstrap 8 regions processes CPU-bound pure Python; one GIL per process2,000 chat connections asyncio thousands of waiting tasks, one threadstandardize 5 million floats vectorize NumPy runs the math in Cpartner API, max 5 parallel asyncio async app; Semaphore(5) keeps the limitHow it works:
- Downloads wait for the network. Threads overlap the waits, and the blocking
requestslibrary works in threads as it is. - A pure Python statistic is CPU-bound. Threads would take turns on the GIL; processes run on separate cores.
- 2,000 connections would need 2,000 threads. asyncio handles them as cheap tasks in one thread, and the framework is async already.
- Standardizing an array is one NumPy expression,
(x - x.mean()) / x.std(), which runs in C and is far faster than any pool of Python workers. - In async code, add a semaphore to respect the limit. In threaded code,
max_workers=5does the same.
Alternative: scenario 1 also works with asyncio and httpx.AsyncClient. Choose it if the rest of the program is async. In a plain script, a thread pool around requests is less code.
M15-C07 · Limit concurrent requests with a semaphore
Section titled “M15-C07 · Limit concurrent requests with a semaphore”A reporting API returns one store’s total revenue per request and takes 0.1 s to answer. It allows at most 3 requests in flight. Precompute the totals from data/sales.csv as the “server data”. Write fetch_store(semaphore, store_id) that waits inside async with semaphore: and counts the requests in flight. Fetch all 12 stores with gather, then print the top 3 stores and the maximum number of requests in flight.
S07: 468,290.16S01: 406,532.46S10: 401,382.78Max in flight: 3server_data: dict[str, float] = defaultdict(float)for line in load_csv("data/sales.csv"): server_data[line["store_id"]] += float(line["revenue"])
in_flight = 0max_in_flight = 0
async def fetch_store(semaphore: asyncio.Semaphore, store_id: str) -> float: global in_flight, max_in_flight # TODO: inside the semaphore: count in flight, sleep 0.1 s, return the total ...
async def main() -> list[float]: # TODO: create Semaphore(3) and gather all 12 stores in order S01..S12 ...
# TODO: run main(), print the top 3 stores and max_in_flightHint 1
Increase in_flight after you enter the semaphore and decrease it before you leave. Update max_in_flight = max(max_in_flight, in_flight) in between.
Hint 2
Create the semaphore inside main(), so it belongs to the event loop that asyncio.run() creates. sorted(server_data) gives the store IDs in order.
Solution
server_data: dict[str, float] = defaultdict(float)for line in load_csv("data/sales.csv"): server_data[line["store_id"]] += float(line["revenue"])
in_flight = 0max_in_flight = 0
async def fetch_store(semaphore: asyncio.Semaphore, store_id: str) -> float: global in_flight, max_in_flight async with semaphore: in_flight += 1 max_in_flight = max(max_in_flight, in_flight) await asyncio.sleep(0.1) # the API answers in_flight -= 1 return round(server_data[store_id], 2)
async def main() -> list[float]: semaphore = asyncio.Semaphore(3) return await asyncio.gather(*(fetch_store(semaphore, s) for s in store_ids))
store_ids = sorted(server_data)start = time.perf_counter()totals = dict(zip(store_ids, asyncio.run(main()), strict=True))elapsed = time.perf_counter() - starttop = sorted(totals.items(), key=lambda kv: kv[1], reverse=True)[:3]for store_id, revenue in top: print(f"{store_id}: {revenue:>11,.2f}")print("Max in flight:", max_in_flight)assert max_in_flight == 3assert 0.35 < elapsed < 0.8 # 12 requests in 4 waves of 3S07: 468,290.16S01: 406,532.46S10: 401,382.78Max in flight: 3How it works:
- The semaphore has 3 permits. The fourth request waits at
async with semaphore:until one of the first three leaves the block. - 12 requests in waves of 3 take about 4 × 0.1 s. Without the semaphore, they would all run at once and take 0.1 s, and
max_in_flightwould be 12. - The counter is safe without a lock: asyncio switches tasks only at
await, and the+= 1line has none. gatherkeeps the order ofstore_ids, sozippairs each store with its own total.
Alternative: asyncio.BoundedSemaphore(3) works the same and raises an error if code releases it more often than it acquired it, which catches bugs in hand-written acquire()/release() code.
M15-C08 · Churn-rate confidence intervals with a process pool
Section titled “M15-C08 · Churn-rate confidence intervals with a process pool”For each contract type in data/customers.csv, estimate a 95% bootstrap confidence interval of the churn rate: draw the customers’ churned flags (0 or 1) with replacement 2,000 times and take the 2.5% and 97.5% positions of the sorted rates. The work is CPU-bound, so run one task per contract type in a ProcessPoolExecutor. Write it as a script with a main guard, print one line per contract and check that the result equals a sequential run.
month-to-month churn 29.6% 95% CI 27.9% to 31.2%one-year churn 8.8% 95% CI 7.3% to 10.4%two-year churn 3.2% 95% CI 2.2% to 4.3%Same as sequential: True# churn_ci.pyimport csvimport randomfrom collections import defaultdictfrom concurrent.futures import ProcessPoolExecutor
def load_flags(path: str) -> dict[str, list[int]]: # TODO: churned flags (int) grouped by contract, sorted by contract name ...
def churn_ci(flags: list[int]) -> tuple[float, float, float]: # TODO: return (rate, low, high) with random.Random(42) and 2,000 resamples ...
def main() -> None: # TODO: load, run churn_ci per contract in a process pool, print, compare ...
# TODO: the main guardHint 1
rng.choices(flags, k=len(flags)) draws one resample. Its churn rate is sum(sample) / len(sample).
Hint 2
pool.map(churn_ci, groups.values()) returns the results in the order of the groups. Seed a new random.Random(42) inside churn_ci, so every process gives the same numbers as a sequential run.
Solution
# churn_ci.py: bootstrap churn-rate intervals per contract type in a process pool.import csvimport randomfrom collections import defaultdictfrom concurrent.futures import ProcessPoolExecutor
RESAMPLES = 2_000
def load_flags(path: str) -> dict[str, list[int]]: """Churned flags (0 or 1) grouped by contract, sorted by contract name.""" flags: dict[str, list[int]] = defaultdict(list) with open(path, newline="", encoding="utf-8") as f: for row in csv.DictReader(f): flags[row["contract"]].append(int(row["churned"])) return dict(sorted(flags.items()))
def churn_ci(flags: list[int]) -> tuple[float, float, float]: """Churn rate and its 95% bootstrap interval.""" rng = random.Random(42) # own seed per task: same result in any process n = len(flags) rates = sorted(sum(rng.choices(flags, k=n)) / n for _ in range(RESAMPLES)) low = rates[int(0.025 * RESAMPLES)] high = rates[int(0.975 * RESAMPLES) - 1] return sum(flags) / n, low, high
def main() -> None: groups = load_flags("data/customers.csv") with ProcessPoolExecutor(max_workers=3) as pool: parallel = list(pool.map(churn_ci, groups.values())) for contract, (rate, low, high) in zip(groups, parallel, strict=True): print(f"{contract:<15} churn {rate:6.1%} 95% CI {low:6.1%} to {high:6.1%}") sequential = [churn_ci(flags) for flags in groups.values()] print("Same as sequential:", parallel == sequential) assert parallel == sequential
if __name__ == "__main__": main()month-to-month churn 29.6% 95% CI 27.9% to 31.2%one-year churn 8.8% 95% CI 7.3% to 10.4%two-year churn 3.2% 95% CI 2.2% to 4.3%Same as sequential: TrueHow it works:
load_flagsgroups the 5,000 flags by contract. Sorting the dict by key fixes the order of the tasks.churn_ciis a top-level function. pickle sends only its module and name, and each worker imports it fromchurn_ci.py.- Each task creates its own
random.Random(42). The parallel result is therefore exactly the sequential result. - The intervals do not overlap: month-to-month customers churn far more often, and the difference is not noise.
- The main guard keeps the workers from starting pools of their own when they import the script.
Alternative: NumPy draws all resamples at once: rng.choice(flags, size=(2_000, n)).mean(axis=1) with np.random.default_rng(42). It runs in C and needs no process pool at all (module 23).
M15-C09 · Fix the bug: a process pool that cannot start
Section titled “M15-C09 · Fix the bug: a process pool that cannot start”Fix the bug: this script should total the revenue per region in a process pool, one task per region. On macOS and Windows it fails at once. Find both bugs, fix them and print the regions sorted by revenue, largest first.
East 993,683.72South 891,766.07North 888,229.47West 822,844.57# region_pool.pyimport csvfrom collections import defaultdictfrom concurrent.futures import ProcessPoolExecutor
with open("data/sales.csv", newline="", encoding="utf-8") as f: revenue_by_region = defaultdict(list) for row in csv.DictReader(f): revenue_by_region[row["region"]].append(float(row["revenue"]))
with ProcessPoolExecutor(max_workers=4) as pool: totals = list(pool.map(lambda values: round(sum(values), 2), revenue_by_region.values()))for region, total in zip(revenue_by_region, totals): print(region, total)Hint 1
With the spawn start method, each worker imports the script. What does the import run?
Hint 2
Process pools send the task function with pickle, by its module and name. Does a lambda have a name a worker can import?
Solution
# region_pool.py: total revenue per region, one task per region.import csvfrom collections import defaultdictfrom concurrent.futures import ProcessPoolExecutor
def region_total(values: list[float]) -> float: """A top-level function: workers can import it by name.""" return round(sum(values), 2)
def main() -> None: revenue_by_region: dict[str, list[float]] = defaultdict(list) with open("data/sales.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): revenue_by_region[row["region"]].append(float(row["revenue"]))
with ProcessPoolExecutor(max_workers=4) as pool: totals = list(pool.map(region_total, revenue_by_region.values())) ranked = sorted(zip(revenue_by_region, totals, strict=True), key=lambda x: -x[1]) for region, total in ranked: print(f"{region:<6} {total:>12,.2f}") assert [region for region, _ in ranked] == ["East", "South", "North", "West"]
if __name__ == "__main__": # workers import this file; only the parent runs main() main()East 993,683.72South 891,766.07North 888,229.47West 822,844.57How it works:
- Bug 1: no main guard. Each spawned worker imports the script, which reads the CSV and starts a new pool at import time. Python stops this with a
RuntimeErrorthat mentions the “bootstrapping phase”. The fix moves the work intomain()behindif __name__ == "__main__":. - Bug 2: a lambda as the task. pickle stores a function by reference: its module and name. A
lambdahas the name<lambda>, which no worker can import, so pickling fails. The fix is the top-level functionregion_total. - Reading the file in
main()also means that the workers do not read it again: they receive only their own list of values. - East has the most revenue and West the least; the assert checks this ranking.
Alternative: summing 20,228 floats takes about a millisecond, much less than starting four processes. In real code, this job needs no pool: sum() per region in one process is faster. The fix is about the two bugs, which appear in every process pool script, large or small.
M15-C10 · Refactor: a retry queue with deque
Section titled “M15-C10 · Refactor: a retry queue with deque”Refactor: a monitoring job processes the 8,064 readings of data/sensors.csv first in, first out. A reading whose status is not ok goes back to the end of the queue once, for a second check. The starter uses a list with pop(0). Rewrite the queue with collections.deque. Check that both versions process the same readings in the same order, count the checks, and show with timeit (3 runs each) that the deque version is faster.
Checks: 8,541 (477 re-checks)Last check: 2024-05-14T23:50:00 S4Same order: Truedeque is faster: Truereadings = load_csv("data/sensors.csv")
def process_list(rows: list[dict[str, str]]) -> list[str]: queue = [(row, 1) for row in rows] # (reading, attempt) checked: list[str] = [] while queue: row, attempt = queue.pop(0) # O(n): every other item moves checked.append(f"{row['timestamp']} {row['sensor_id']}") if row["status"] != "ok" and attempt == 1: queue.append((row, 2)) # check it once more, at the end return checked
# TODO: process_deque with the same logic and a deque# TODO: print the number of checks, the number of re-checks,# "Same order:" and "deque is faster:"Hint 1
deque(iterable) builds the queue. popleft() replaces pop(0) and append() stays the same.
Hint 2
The re-checks are the checks beyond one per reading: len(checked) - len(readings). Time each version with timeit.timeit(lambda: process_list(readings), number=3).
Solution
readings = load_csv("data/sensors.csv")
def process_list(rows: list[dict[str, str]]) -> list[str]: queue = [(row, 1) for row in rows] # (reading, attempt) checked: list[str] = [] while queue: row, attempt = queue.pop(0) # O(n): every other item moves checked.append(f"{row['timestamp']} {row['sensor_id']}") if row["status"] != "ok" and attempt == 1: queue.append((row, 2)) # check it once more, at the end return checked
def process_deque(rows: list[dict[str, str]]) -> list[str]: queue = deque((row, 1) for row in rows) checked: list[str] = [] while queue: row, attempt = queue.popleft() # O(1): nothing moves checked.append(f"{row['timestamp']} {row['sensor_id']}") if row["status"] != "ok" and attempt == 1: queue.append((row, 2)) return checked
slow, fast = process_list(readings), process_deque(readings)list_s = timeit.timeit(lambda: process_list(readings), number=3)deque_s = timeit.timeit(lambda: process_deque(readings), number=3)print(f"Checks: {len(fast):,} ({len(fast) - len(readings)} re-checks)")print("Last check:", fast[-1])print("Same order:", slow == fast)print("deque is faster:", deque_s < list_s)assert slow == fastassert len(fast) - len(readings) == sum(r["status"] != "ok" for r in readings)Checks: 8,541 (477 re-checks)Last check: 2024-05-14T23:50:00 S4Same order: Truedeque is faster: TrueHow it works:
list.pop(0)removes the first item and moves every other item one step left: per pop, about item moves for the whole queue.deque.popleft()removes the first item in . A deque is built from linked blocks, so nothing moves.- The 477 readings with status
warnorfailare checked twice, so the queue handles 8,541 checks. Both versions see them in exactly the same order, so the refactor changes the speed and nothing else. - The gap grows with the queue. With 8,064 items the list is several times slower; with a million items it would take minutes, and the deque would still take about a second.
Alternative: if the order of the re-checks does not matter, keep two plain lists: process all readings once with a for loop, collect the failures in a second list and loop over it afterwards. Then no item ever leaves the front of a list.
M15-C11 · Count orders above many thresholds with bisect
Section titled “M15-C11 · Count orders above many thresholds with bisect”A pricing analyst wants to know, for 50 thresholds (10, 20, …, 500 USD), how many sales lines have a revenue of at least that threshold. The starter scans all lines once per threshold. Sort the revenues once and use bisect.bisect_left to count each threshold in . Print three of the counts, check that both versions agree and show which is faster with timeit.
revenue >= 50: 13,463 linesrevenue >= 100: 8,395 linesrevenue >= 500: 1,337 linesSame counts: Truebisect is faster: Trueimport bisect
revenues = [float(line["revenue"]) for line in load_csv("data/sales.csv")]thresholds = list(range(10, 501, 10))
def counts_scan() -> list[int]: return [sum(1 for r in revenues if r >= t) for t in thresholds]
def counts_bisect() -> list[int]: # TODO: sort once, then len(values) - bisect_left(values, t) per threshold ...
# TODO: print the counts for 50, 100 and 500, "Same counts:" and "bisect is faster:"Hint 1
In a sorted list, bisect_left(values, t) is the number of values below t. The rest are at least t.
Hint 2
Include the sort inside counts_bisect(), so the timing comparison is fair. Time each function with timeit.timeit(counts_scan, number=3).
Solution
import bisect
revenues = [float(line["revenue"]) for line in load_csv("data/sales.csv")]thresholds = list(range(10, 501, 10))
def counts_scan() -> list[int]: return [sum(1 for r in revenues if r >= t) for t in thresholds]
def counts_bisect() -> list[int]: values = sorted(revenues) # O(n log n), once return [len(values) - bisect.bisect_left(values, t) for t in thresholds]
scan, fast = counts_scan(), counts_bisect()by_threshold = dict(zip(thresholds, fast, strict=True))for t in (50, 100, 500): print(f"revenue >= {t:>3}: {by_threshold[t]:>6,} lines")scan_s = timeit.timeit(counts_scan, number=3)bisect_s = timeit.timeit(counts_bisect, number=3)print("Same counts:", scan == fast)print("bisect is faster:", bisect_s < scan_s)assert scan == fastassert by_threshold[10] >= by_threshold[500]revenue >= 50: 13,463 linesrevenue >= 100: 8,395 linesrevenue >= 500: 1,337 linesSame counts: Truebisect is faster: TrueHow it works:
- The scan reads 20,228 values for each of 50 thresholds: about a million comparisons, .
- The bisect version sorts once, , then does 50 binary searches of about 15 steps each.
bisect_leftreturns the position of the first value that is>= t, solen(values) - positioncounts the values at or abovet.- Module 17 explains binary search and
bisectin depth.
Alternative: with NumPy, np.searchsorted(np.sort(arr), thresholds) does all 50 searches in one vectorized call.
M15-C12 · Predict the output: when coroutines run
Section titled “M15-C12 · Predict the output: when coroutines run”Predict the output: write down the seven lines this program prints, in order. step() prints a line, waits, prints another line and returns its name.
Acceptance criteria:
- Write your prediction line by line, then run the code.
- Your prediction matches the Output in the solution, line by line.
async def step(name: str, delay: float) -> str: print(f"{name} start") await asyncio.sleep(delay) print(f"{name} end") return name
async def main() -> None: first = await step("load", 0.1) rest = await asyncio.gather(step("clean", 0.2), step("score", 0.1)) print(first, rest)
asyncio.run(main())Hint 1
await step("load", 0.1) on its own waits until load is completely done before the next line runs.
Hint 2
gather starts clean and score together. Which one finishes its wait first? In which order does gather return the names?
Solution
async def step(name: str, delay: float) -> str: print(f"{name} start") await asyncio.sleep(delay) print(f"{name} end") return name
async def main() -> tuple[str, list[str]]: first = await step("load", 0.1) rest = await asyncio.gather(step("clean", 0.2), step("score", 0.1)) print(first, rest) return first, rest
result = asyncio.run(main())assert result == ("load", ["clean", "score"])load startload endclean startscore startscore endclean endload ['clean', 'score']How it works:
await step("load", 0.1)runsloadfrom start to end. Nothing else is scheduled yet, so nothing else runs meanwhile.gatherstartsclean, which prints and awaits, thenscore, which prints and awaits. Both waits overlap.scorewaits 0.1 s and ends first;cleanends at 0.2 s.gatherreturns["clean", "score"]: the order of its arguments, not the finish order.
Alternative: to start load concurrently with the others, put it inside the same gather. Use separate await lines only when a step needs the result of the step before it, as “clean” needs the loaded data.
Challenge
Section titled “Challenge”M15-X01 · Write a small benchmark harness
Section titled “M15-X01 · Write a small benchmark harness”Write benchmark(funcs, data, number=5, repeat=3). For each function, it calls timeit.repeat() with functools.partial(func, data), keeps the best time per call and returns (name, seconds) pairs, fastest first. Use it on three ways to list the distinct customer IDs of the first 5,000 sales lines in first-seen order: with a list and in, with a helper set, and with dict.fromkeys(). Print the name of the slowest function, check that all three agree and that the slowest is at least 10 times slower than the fastest.
Distinct customers: 1417Slowest: unique_listAll agree: TrueSlowest is 10x slower: Truefrom collections.abc import Callablefrom functools import partial
ids = [line["customer_id"] for line in load_csv("data/sales.csv")[:5_000]]
def unique_list(values: list[str]) -> list[str]: seen: list[str] = [] for value in values: if value not in seen: seen.append(value) return seen
def unique_set(values: list[str]) -> list[str]: # TODO: a list for the order plus a set for fast membership ...
def unique_dict(values: list[str]) -> list[str]: # TODO: dict.fromkeys keeps the first-seen order ...
def benchmark(funcs, data, number=5, repeat=3) -> list[tuple[str, float]]: # TODO: best time per call for each function, fastest first ...
# TODO: print the slowest, "All agree:", "Slowest is 10x slower:"Hint 1
min(timeit.repeat(partial(func, data), number=number, repeat=repeat)) / number is the best time per call. Use func.__name__ as the name.
Hint 2
list(dict.fromkeys(values)) removes duplicates and keeps the first occurrence of each value, because dicts keep insertion order.
Solution
from collections.abc import Callablefrom functools import partial
ids = [line["customer_id"] for line in load_csv("data/sales.csv")[:5_000]]
def unique_list(values: list[str]) -> list[str]: seen: list[str] = [] for value in values: if value not in seen: # O(len(seen)) for every value seen.append(value) return seen
def unique_set(values: list[str]) -> list[str]: seen: set[str] = set() result: list[str] = [] for value in values: if value not in seen: # O(1) seen.add(value) result.append(value) return result
def unique_dict(values: list[str]) -> list[str]: return list(dict.fromkeys(values))
def benchmark( funcs: list[Callable[[list[str]], list[str]]], data: list[str], number: int = 5, repeat: int = 3,) -> list[tuple[str, float]]: results = [] for func in funcs: times = timeit.repeat(partial(func, data), number=number, repeat=repeat) results.append((func.__name__, min(times) / number)) return sorted(results, key=lambda item: item[1])
funcs = [unique_list, unique_set, unique_dict]ranking = benchmark(funcs, ids)outputs = [func(ids) for func in funcs]print("Distinct customers:", len(outputs[0]))print("Slowest:", ranking[-1][0])print("All agree:", outputs[0] == outputs[1] == outputs[2])print("Slowest is 10x slower:", ranking[-1][1] > 10 * ranking[0][1])assert ranking[-1][0] == "unique_list"Distinct customers: 1417Slowest: unique_listAll agree: TrueSlowest is 10x slower: TrueHow it works:
partial(func, data)builds a function with no arguments, which is whattimeitcalls.min(...) / numberis the best time per call: the run with the least noise from other programs.unique_listchecks membership in a growing list: forudistinct values. The other two are .- The harness prints only the safe facts: the slowest function and a 10× gap. The order of
unique_setandunique_dictis close and can change between machines, so the solution does not print it.
Alternative: for serious benchmarks, use a tool such as pytest-benchmark or pyperf. They warm up the code, run it many times and report statistics such as the median and the spread.
M15-X02 · Speed up a sensor spike detector
Section titled “M15-X02 · Speed up a sensor spike detector”The starter flags a temperature reading as a spike when it is more than 6.0 °C above the mean of the 36 readings before it (6 hours). It is slow. Profile it on all four sensors of data/sensors.csv and print the call counts of flag_spikes and of statistics.mean. Then write flag_spikes_fast with a running sum, check that it flags the same readings and that it is at least 5 times faster.
flag_spikes calls: 4statistics.mean calls: 7898Spikes per sensor: {'S1': 8, 'S2': 12, 'S3': 11, 'S4': 8}Same spikes: TrueAt least 5x faster: Trueimport cProfileimport pstatsimport statistics
temps: dict[str, list[float]] = defaultdict(list)for row in load_csv("data/sensors.csv"): if row["temperature_c"]: temps[row["sensor_id"]].append(float(row["temperature_c"]))
def flag_spikes(values: list[float], window: int = 36, jump: float = 6.0) -> list[int]: return [ i for i in range(window, len(values)) if values[i] - statistics.mean(values[i - window : i]) > jump ]
# TODO: profile flag_spikes over the four sensors; print ncalls of flag_spikes and mean# TODO: flag_spikes_fast with a running sum of the last `window` values# TODO: print the spikes per sensor, "Same spikes:" and "At least 5x faster:"Hint 1
The profile shows mean called once per reading. statistics.mean is exact: it converts floats to fractions internally, which makes it far slower than sum() / len().
Hint 2
Start with total = sum(values[:window]). For each i, compare values[i] - total / window, then update total += values[i] - values[i - window].
Solution
import cProfileimport pstatsimport statistics
temps: dict[str, list[float]] = defaultdict(list)for row in load_csv("data/sensors.csv"): if row["temperature_c"]: temps[row["sensor_id"]].append(float(row["temperature_c"]))sensors = sorted(temps)
def flag_spikes(values: list[float], window: int = 36, jump: float = 6.0) -> list[int]: return [ i for i in range(window, len(values)) if values[i] - statistics.mean(values[i - window : i]) > jump ]
def flag_spikes_fast( values: list[float], window: int = 36, jump: float = 6.0) -> list[int]: flagged = [] total = sum(values[:window]) # sum of the `window` readings before i for i in range(window, len(values)): if values[i] - total / window > jump: flagged.append(i) total += values[i] - values[i - window] # slide the window by one return flagged
with cProfile.Profile() as profiler: slow = {s: flag_spikes(temps[s]) for s in sensors}funcs = pstats.Stats(profiler).get_stats_profile().func_profilesprint("flag_spikes calls:", funcs["flag_spikes"].ncalls)print("statistics.mean calls:", funcs["mean"].ncalls)
fast = {s: flag_spikes_fast(temps[s]) for s in sensors}print("Spikes per sensor:", {s: len(flags) for s, flags in fast.items()})print("Same spikes:", fast == slow)slow_s = timeit.timeit(lambda: [flag_spikes(temps[s]) for s in sensors], number=1)fast_s = timeit.timeit(lambda: [flag_spikes_fast(temps[s]) for s in sensors], number=1)print("At least 5x faster:", slow_s > 5 * fast_s)assert fast == slowassert int(funcs["mean"].ncalls) == sum(len(temps[s]) - 36 for s in sensors)flag_spikes calls: 4statistics.mean calls: 7898Spikes per sensor: {'S1': 8, 'S2': 12, 'S3': 11, 'S4': 8}Same spikes: TrueAt least 5x faster: TrueHow it works:
- Profile.
flag_spikesruns 4 times, once per sensor, butstatistics.meanruns once per reading: almost 8,000 times. Its own helper functions fill the rest of the profile. That is the hotspot. - Two costs. Each call slices 36 values () and then computes an exact mean through fractions, which is slow per value.
statistics.fmeanwould remove most of the second cost; the running sum removes both. - Running sum. Moving the window by one reading adds the new value and subtracts the oldest one: per reading instead of .
- Same result. The running sum collects tiny float errors, so the means differ in the last digits. No reading lies that close to the 6.0 °C threshold, so the flags are identical. Always check that an optimized version gives the same answer.
Alternative: pandas does the same in one line: s - s.rolling(36).mean().shift(1) > 6.0 (module 25). shift(1) makes the window end before the current reading, as in this exercise.
M15-X03 · An async fetcher with retries and a rate limit
Section titled “M15-X03 · An async fetcher with retries and a rate limit”A product API serves data/products.csv in 8 pages of 4 products (the last page has 2). It allows 3 requests in flight, and it is flaky: page 2 and page 5 fail once with ConnectionError, and page 7 fails twice. Write fetch_with_retry(semaphore, page). It tries up to 3 times, waits 0.01 * 2 ** attempt seconds between tries (exponential backoff), and holds the semaphore only during a request. Fetch all pages with gather and print the number of products, the attempts per page and the maximum number of requests in flight.
Products: 30 P001 ... P030Attempts: {1: 1, 2: 2, 3: 1, 4: 1, 5: 2, 6: 1, 7: 3, 8: 1}Total requests: 12Max in flight: 3PRODUCT_IDS = [row["product_id"] for row in load_csv("data/products.csv")]failures_left = {2: 1, 5: 1, 7: 2} # how often each page still failsattempts: Counter[int] = Counter()in_flight = 0max_in_flight = 0
async def fetch_page(page: int) -> list[str]: """Simulated API call: 30 ms, then 4 product IDs, or a ConnectionError.""" global in_flight, max_in_flight in_flight += 1 max_in_flight = max(max_in_flight, in_flight) attempts[page] += 1 await asyncio.sleep(0.03) in_flight -= 1 if failures_left.get(page, 0) > 0: failures_left[page] -= 1 raise ConnectionError(f"page {page}: connection reset") return PRODUCT_IDS[(page - 1) * 4 : page * 4]
async def fetch_with_retry(semaphore: asyncio.Semaphore, page: int) -> list[str]: # TODO: up to 3 tries; the semaphore only around fetch_page; backoff between ...
# TODO: main() with Semaphore(3) and gather over pages 1..8; print the resultsHint 1
Loop for attempt in range(3):. Inside, async with semaphore: return await fetch_page(page) in a try block. In except ConnectionError, re-raise on the last attempt, else await asyncio.sleep(...).
Hint 2
Do the backoff sleep outside the async with semaphore: block. A task that waits to retry should not hold a permit that another page could use.
Hint 3
Flatten the 8 lists from gather with [pid for page in pages for pid in page], and print dict(sorted(attempts.items())).
Solution
PRODUCT_IDS = [row["product_id"] for row in load_csv("data/products.csv")]failures_left = {2: 1, 5: 1, 7: 2} # how often each page still failsattempts: Counter[int] = Counter()in_flight = 0max_in_flight = 0
async def fetch_page(page: int) -> list[str]: """Simulated API call: 30 ms, then 4 product IDs, or a ConnectionError.""" global in_flight, max_in_flight in_flight += 1 max_in_flight = max(max_in_flight, in_flight) attempts[page] += 1 await asyncio.sleep(0.03) in_flight -= 1 if failures_left.get(page, 0) > 0: failures_left[page] -= 1 raise ConnectionError(f"page {page}: connection reset") return PRODUCT_IDS[(page - 1) * 4 : page * 4]
async def fetch_with_retry( semaphore: asyncio.Semaphore, page: int, tries: int = 3) -> list[str]: for attempt in range(tries): try: async with semaphore: # hold a permit only during the request return await fetch_page(page) except ConnectionError: if attempt == tries - 1: raise # out of tries: let the caller see the error await asyncio.sleep(0.01 * 2**attempt) # backoff: 10 ms, then 20 ms raise AssertionError("unreachable")
async def main() -> list[list[str]]: semaphore = asyncio.Semaphore(3) return await asyncio.gather(*(fetch_with_retry(semaphore, p) for p in range(1, 9)))
pages = asyncio.run(main())products = [pid for page in pages for pid in page]print("Products:", len(products), products[0], "...", products[-1])print("Attempts:", dict(sorted(attempts.items())))print("Total requests:", attempts.total())print("Max in flight:", max_in_flight)assert products == PRODUCT_IDSassert max_in_flight <= 3Products: 30 P001 ... P030Attempts: {1: 1, 2: 2, 3: 1, 4: 1, 5: 2, 6: 1, 7: 3, 8: 1}Total requests: 12Max in flight: 3How it works:
- Each page tries up to 3 times. A
ConnectionErroron the last try is re-raised, sogatherwould fail loudly instead of returning a page with missing products. - The backoff waits 10 ms after the first failure and 20 ms after the second. Exponential backoff gives a struggling server more and more room.
- The semaphore wraps only the request. A page that waits to retry releases its permit, so other pages keep the 3 slots busy.
- Page 7 needs 3 attempts, pages 2 and 5 need 2, the others 1: 12 requests for 8 pages. The counts are deterministic, because the failures are scripted.
gatherreturns the pages in order 1 to 8, so the flattened list equals the product list exactly.Counter.total()(Python 3.10+) adds up all counts.
Alternative: libraries such as tenacity provide retry decorators with backoff, jitter (a random part in the wait, so that many clients do not retry at the same moment) and limits. Module 16 uses retries against real HTTP status codes such as 429 and 503.
M15-X04 · Chunk work for a process pool
Section titled “M15-X04 · Chunk work for a process pool”Score all 5,000 customers of data/customers.csv for churn risk with a small Monte Carlo simulation: for each customer, draw 300 noisy versions of a risk index and count how often the index exceeds 1.0. Seed each customer’s random.Random with the number in its ID, so the scores do not depend on how the work is split. Split the customers into 8 chunks, score the chunks in a ProcessPoolExecutor, and check that the result equals a sequential run. Print the 3 riskiest customers and the number of customers with a risk above 0.5.
Chunks: 8 of 625Riskiest: [('C03634', 1.0), ('C04855', 1.0), ('C04925', 1.0)]Risk above 0.5: 1402Same as sequential: True# risk_chunks.pyimport csvimport randomfrom concurrent.futures import ProcessPoolExecutor
def risk(customer: dict[str, str]) -> float: """Share of 300 noisy draws where the risk index exceeds 1.0.""" rng = random.Random(int(customer["customer_id"][1:])) base = ( 0.04 * float(customer["support_tickets"]) + 0.5 * (customer["contract"] == "month-to-month") + 0.01 * float(customer["monthly_charges"]) - 0.01 * float(customer["tenure_months"]) ) hits = sum(base + rng.gauss(0, 0.3) > 1.0 for _ in range(300)) return hits / 300
def score_chunk(chunk: list[dict[str, str]]) -> list[tuple[str, float]]: # TODO: (customer_id, risk) for each customer of the chunk ...
def main() -> None: # TODO: load customers, split into 8 chunks, score with a pool, compare, print ...
if __name__ == "__main__": main()Hint 1
Split a list into k chunks with a slice step: [customers[i::k] for i in range(k)], or with consecutive slices of ceil(n / k) rows. Either works, because each customer’s seed is its own.
Hint 2
pool.map(score_chunk, chunks) returns one list per chunk. Flatten and sort by customer ID before you compare with the sequential result.
Solution
# risk_chunks.py: Monte Carlo churn risk for 5,000 customers, in 8 chunks.import csvimport randomfrom concurrent.futures import ProcessPoolExecutor
def risk(customer: dict[str, str]) -> float: """Share of 300 noisy draws where the risk index exceeds 1.0.""" rng = random.Random(int(customer["customer_id"][1:])) base = ( 0.04 * float(customer["support_tickets"]) + 0.5 * (customer["contract"] == "month-to-month") + 0.01 * float(customer["monthly_charges"]) - 0.01 * float(customer["tenure_months"]) ) hits = sum(base + rng.gauss(0, 0.3) > 1.0 for _ in range(300)) return hits / 300
def score_chunk(chunk: list[dict[str, str]]) -> list[tuple[str, float]]: return [(customer["customer_id"], risk(customer)) for customer in chunk]
def main() -> None: with open("data/customers.csv", newline="", encoding="utf-8") as f: customers = list(csv.DictReader(f)) chunk_size = -(-len(customers) // 8) # ceiling division: 625 chunks = [ customers[i : i + chunk_size] for i in range(0, len(customers), chunk_size) ]
with ProcessPoolExecutor(max_workers=4) as pool: results = pool.map(score_chunk, chunks) # one list per chunk, in order parallel = sorted(pair for part in results for pair in part) sequential = sorted(score_chunk(customers))
riskiest = sorted(parallel, key=lambda pair: (-pair[1], pair[0]))[:3] print("Chunks:", len(chunks), "of", chunk_size) print("Riskiest:", [(cid, round(score, 3)) for cid, score in riskiest]) print("Risk above 0.5:", sum(score > 0.5 for _, score in parallel)) print("Same as sequential:", parallel == sequential) assert parallel == sequential
if __name__ == "__main__": main()Chunks: 8 of 625Riskiest: [('C03634', 1.0), ('C04855', 1.0), ('C04925', 1.0)]Risk above 0.5: 1402Same as sequential: TrueHow it works:
- Seeds per item. Each customer’s random stream depends only on its own ID. So the result is the same for 1 chunk, 8 chunks or 5,000 tasks, and the parallel run can be checked against the sequential one exactly.
- Chunks. 8 tasks of 625 customers each send little data and each do a lot of work. 5,000 tasks of one customer would spend more time on pickling and messages than on scoring.
- Order.
pool.mapreturns the chunk results in chunk order. Flattening and sorting by ID gives a stable result for the comparison and the report. max_workers=4uses at most 4 cores. Leave a core free for the rest of the machine when you run long jobs on a laptop.
Alternative: pool.map(risk, customers, chunksize=625) does the chunking for you: the executor sends the items in batches of 625 to the workers and returns one result per customer, in order.
M15-X05 · Mix blocking code into async code with to_thread
Section titled “M15-X05 · Mix blocking code into async code with to_thread”An async report service must, at the same time, call three API endpoints (simulated with asyncio.sleep(0.2)) and read the six monthly report files in data/reports/, which sit on a slow network drive. The starter’s file reader is blocking (time.sleep(0.2), then csv), and calling it inside a coroutine freezes the event loop. Run each blocking read with asyncio.to_thread(), gather everything at once and check that the whole run takes less than 0.6 s. The buggy version takes about 1.2 s, and running all nine steps one after another about 1.8 s. Print the API results and the six report totals.
['/stores: ok', '/products: ok', '/forecast: ok']2024-01: 14,162.332024-02: 4,719.042024-03: 12,296.722024-04: 10,879.042024-05: 6,675.862024-06: 8,533.40Under 0.6 s: Truefrom pathlib import Path
def read_report(path: Path) -> tuple[str, float]: """Blocking: waits for the network drive, then parses the file.""" time.sleep(0.2) with path.open(newline="", encoding="utf-8") as f: return path.stem, round(sum(float(r["revenue"]) for r in csv.DictReader(f)), 2)
async def call_api(endpoint: str) -> str: await asyncio.sleep(0.2) return f"{endpoint}: ok"
async def read_report_async(path: Path) -> tuple[str, float]: return read_report(path) # bug: blocks the event loop
async def main() -> tuple[list[str], list[tuple[str, float]]]: paths = sorted(Path("data/reports").glob("2024-*.csv")) # TODO: gather the three API calls and the six reports in one gather ...Hint 1
await asyncio.to_thread(read_report, path) runs the blocking function in a worker thread and lets the event loop run other tasks meanwhile.
Hint 2
Put all nine awaitables into one gather: await asyncio.gather(*api_calls, *report_reads). Then split the result list at index 3.
Solution
from pathlib import Path
def read_report(path: Path) -> tuple[str, float]: """Blocking: waits for the network drive, then parses the file.""" time.sleep(0.2) with path.open(newline="", encoding="utf-8") as f: return path.stem, round(sum(float(r["revenue"]) for r in csv.DictReader(f)), 2)
async def call_api(endpoint: str) -> str: await asyncio.sleep(0.2) return f"{endpoint}: ok"
async def read_report_async(path: Path) -> tuple[str, float]: return await asyncio.to_thread(read_report, path) # runs in a worker thread
async def main() -> tuple[list[str], list[tuple[str, float]]]: paths = sorted(Path("data/reports").glob("2024-*.csv")) endpoints = ["/stores", "/products", "/forecast"] results = await asyncio.gather( *(call_api(e) for e in endpoints), *(read_report_async(p) for p in paths), ) return results[:3], results[3:]
start = time.perf_counter()api_results, reports = asyncio.run(main())elapsed = time.perf_counter() - startprint(api_results)for month, total in reports: print(f"{month}: {total:>10,.2f}")print("Under 0.6 s:", elapsed < 0.6)assert len(reports) == 6 and reports[0] == ("2024-01", 14162.33)assert elapsed < 0.6['/stores: ok', '/products: ok', '/forecast: ok']2024-01: 14,162.332024-02: 4,719.042024-03: 12,296.722024-04: 10,879.042024-05: 6,675.862024-06: 8,533.40Under 0.6 s: TrueHow it works:
- The buggy
read_report_asynccalls the blocking function directly. Eachtime.sleep(0.2)freezes the event loop, so the six reads run one after another: about 1.2 s. The API waits overlap with them, so they add almost nothing. asyncio.to_threadhands the call to a thread of the loop’s default thread pool and returns an awaitable. The loop keeps running the API coroutines while the threads wait.- All nine waits overlap: the run takes about 0.2 s.
gatherreturns the nine results in argument order, so the first three are the API results and the last six are the reports, in month order.
Alternative: the event loop’s executor API does the same in older code: await asyncio.get_running_loop().run_in_executor(None, read_report, path). to_thread (Python 3.9+) is the shorter modern form. For CPU-bound blocking work, pass a ProcessPoolExecutor to run_in_executor instead of None.