Skip to content

15. Performance and concurrency — Mini-project

Every night, a script builds the sales report of the first half of 2024. It reads six monthly files from a network drive, adds the city of each store, and computes a bootstrap confidence interval of the mean line revenue for each product category. The script works, but the operations team wants it faster: it will soon run on 10 years of files.

Your job: make the report at least 3 times faster without changing a single character of its output. Do not guess. Profile the script first, then fix what the profile shows, with the right tool for each kind of slowness.

The project uses the whole module: timing with perf_counter, profiling with cProfile and pstats, dict indexes instead of scans, a ThreadPoolExecutor for I/O-bound work, a ProcessPoolExecutor for CPU-bound work, the main guard and deterministic results.

The report reads the six files data/reports/2024-01.csv to 2024-06.csv (297 lines in total, columns order_id, order_date, store_id, product, category, quantity, revenue) and data/stores.csv (12 stores). Watch out: 2024-04.csv has the same columns in a different order. csv.DictReader reads columns by name, so the order does not matter.

The network drive is simulated: each file read waits NETWORK_DELAY = 0.2 seconds before it reads the file. This is the slow script, nightly_slow.py. Save it next to your data/ folder and run it:

nightly_slow.py
# nightly_slow.py: the nightly sales report, before any optimization.
import csv
import random
import statistics
import time
from pathlib import Path
NETWORK_DELAY = 0.2 # each file read waits this long for the network drive
RESAMPLES = 10_000 # bootstrap resamples per category
def read_report(path: Path) -> list[dict[str, str]]:
"""Read one monthly report file from the (slow) network drive."""
time.sleep(NETWORK_DELAY)
with path.open(newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
def load_lines(folder: str) -> list[dict[str, str]]:
lines: list[dict[str, str]] = []
for path in sorted(Path(folder).glob("2024-*.csv")):
lines += read_report(path)
return lines
def load_stores(path: str) -> list[dict[str, str]]:
with open(path, newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
def find_city(stores: list[dict[str, str]], store_id: str) -> str:
for store in stores:
if store["store_id"] == store_id:
return store["city"]
raise KeyError(store_id)
def bootstrap_ci(values: list[float]) -> tuple[float, float]:
"""95% bootstrap confidence interval of the mean."""
rng = random.Random(42)
means = []
for _ in range(RESAMPLES):
means.append(statistics.mean(rng.choices(values, k=len(values))))
means.sort()
return means[int(0.025 * RESAMPLES)], means[int(0.975 * RESAMPLES) - 1]
def format_report(
lines: list[dict[str, str]],
revenue_by_city: dict[str, float],
by_category: dict[str, list[float]],
intervals: list[tuple[float, float]],
) -> str:
total = sum(float(line["revenue"]) for line in lines)
top = sorted(revenue_by_city.items(), key=lambda item: item[1], reverse=True)[:3]
out = [
"Nightly sales report, 2024-01 to 2024-06",
f"Lines: {len(lines)} Revenue: {total:,.2f}",
"Top cities: " + ", ".join(f"{city} {rev:,.2f}" for city, rev in top),
f"{'Category':<12}{'lines':>6}{'mean':>9} 95% CI of the mean",
]
for (category, values), (low, high) in zip(
by_category.items(), intervals, strict=True
):
mean = statistics.fmean(values)
out.append(
f"{category:<12}{len(values):>6}{mean:>9.2f} {low:.2f} to {high:.2f}"
)
return "\n".join(out)
def build_report(
folder: str = "data/reports", stores_path: str = "data/stores.csv"
) -> str:
lines = load_lines(folder)
stores = load_stores(stores_path)
revenue_by_city: dict[str, float] = {}
by_category: dict[str, list[float]] = {}
for line in lines:
city = find_city(stores, line["store_id"])
revenue = float(line["revenue"])
revenue_by_city[city] = revenue_by_city.get(city, 0.0) + revenue
by_category.setdefault(line["category"], []).append(revenue)
by_category = dict(sorted(by_category.items()))
intervals = [bootstrap_ci(values) for values in by_category.values()]
return format_report(lines, revenue_by_city, by_category, intervals)
def main() -> None:
start = time.perf_counter()
print(build_report())
print(f"Built in {time.perf_counter() - start:.2f} s")
if __name__ == "__main__":
main()
Output
Nightly sales report, 2024-01 to 2024-06
Lines: 297 Revenue: 57,266.39
Top cities: Seattle 10,532.74, Houston 9,789.25, Philadelphia 5,995.64
Category lines mean 95% CI of the mean
Beauty 44 60.98 44.59 to 81.46
Books 34 35.63 27.54 to 45.21
Clothing 54 72.60 54.73 to 91.87
Electronics 67 479.84 343.33 to 635.17
Home 39 188.30 158.19 to 219.02
Sports 59 168.79 133.18 to 214.92
Built in 2.21 s

The last line is the duration of one run on a laptop. Yours differs. Every other line must stay exactly the same after your changes.

Write nightly_fast.py. It must:

  1. Keep the output of build_report() identical to the slow version, character for character. Import the slow module (import nightly_slow as slow) and compare the two reports in code.
  2. Profile the slow version with cProfile and print the call counts of the functions that matter: read_report, time.sleep, find_city, bootstrap_ci and statistics.mean.
  3. Replace the store scan in find_city with a dict index that is built once.
  4. Read the six files concurrently with a ThreadPoolExecutor, in month order.
  5. Compute the six bootstrap intervals in a ProcessPoolExecutor, one task per category, with a faster mean than statistics.mean, and with the same random draws as the slow version.
  6. Run as a script with if __name__ == "__main__":, with every task function defined at the top level of a module.
  7. Print Same report: True and Speed-up at least 3x: True, measured with time.perf_counter().
  1. Measure the baseline. Run nightly_slow.py twice and note the time. On a laptop it takes a little over 2 seconds.

  2. Profile it. Wrap slow.build_report() in with cProfile.Profile() as profiler:. Print pstats.Stats(profiler).sort_stats("cumulative").print_stats(12) once to read the full table. Then print only the call counts you need from get_stats_profile().func_profiles.

  3. Read the profile. Two things dominate. time.sleep is called 6 times and accounts for about 1.2 seconds: the script waits for the drive, one file after the other. statistics.mean is called 60,000 times (6 categories × 10,000 resamples): that is the CPU cost. find_city runs 297 times over 12 stores, which is cheap today but grows with the data.

  4. Fix the scan. Build city_of = {store_id: city} once and look up each line in O(1)O(1).

  5. Overlap the waits. Read the files with ThreadPoolExecutor(max_workers=6) and pool.map(slow.read_report, paths). map keeps the month order, so the lines and every float sum come out in the same order as before.

  6. Parallelize the bootstrap. Write a top-level bootstrap_ci that seeds random.Random(42) and draws exactly as the slow version, but computes each mean as sum(sample) / n. Run it with ProcessPoolExecutor and pool.map over the categories.

  7. Prove it. Build both reports, compare them with == and print the speed-up check. If the report differs, print both and compare them line by line before you change anything else.

A skeleton to start from:

nightly_fast.py (starter)
# nightly_fast.py: the nightly report, profiled, fixed and run concurrently.
import nightly_slow as slow
def bootstrap_ci(values: list[float]) -> tuple[float, float]:
# TODO: same draws as slow.bootstrap_ci, faster mean
...
def build_report(
folder: str = "data/reports", stores_path: str = "data/stores.csv"
) -> str:
# TODO: threads for the files, a dict index for the cities,
# processes for the bootstrap, then slow.format_report(...)
...
def profile_slow() -> None:
# TODO: profile slow.build_report() and print the call counts
...
def main() -> None:
# TODO: profile, time both versions, print the report and the two checks
...
if __name__ == "__main__":
main()
Criterion Points Full points when
Identical output 3 The fast report equals the slow one, checked with == in code
Profile 3 The script profiles the slow version and prints the five call counts; your notes name the two hotspots
Data structure 2 The store lookup is a dict built once, not a scan per line
Threads for I/O 2 The six files are read with a ThreadPoolExecutor, in month order
Processes for CPU 3 The bootstrap runs in a ProcessPoolExecutor with top-level functions and the main guard
Deterministic 2 Every run prints the same report: seeded random generators, ordered results
Speed-up 2 The run prints Speed-up at least 3x: True
Readability 1 Type hints, short functions, comments that explain why
Total 18 15 or more: you are ready for module 16
  1. Make the network delay 1.0 second and the number of files 24 (copy the six files under new names in a scratch folder). Find the best max_workers for the thread pool by measurement.
  2. Replace the thread pool with asyncio: run each blocking read_report with asyncio.to_thread() and gather the six reads.
  3. Add a --profile command-line flag with argparse that prints the full print_stats(15) table of the slow version.
  4. Move the bootstrap to NumPy: rng.choice(values, size=(10_000, n)).mean(axis=1) with np.random.default_rng(42). The intervals change (another random generator), so compare against a new baseline. Is the process pool still worth it?
  5. Write a pytest test (module 14) that checks build_report() of both versions on a small folder in tmp_path, with NETWORK_DELAY set to 0 through monkeypatch.

Try the project yourself first. Then compare your script with this one. Your structure can differ; your report must not.

Reference solution
nightly_fast.py
# nightly_fast.py: the same report, profiled, fixed and run concurrently.
import cProfile
import csv
import pstats
import random
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from pathlib import Path
import nightly_slow as slow
def bootstrap_ci(values: list[float]) -> tuple[float, float]:
"""Same seed and draws as the slow version; sum() / n instead of statistics.mean."""
rng = random.Random(42)
n = len(values)
means = sorted(sum(rng.choices(values, k=n)) / n for _ in range(slow.RESAMPLES))
return means[int(0.025 * slow.RESAMPLES)], means[int(0.975 * slow.RESAMPLES) - 1]
def build_report(
folder: str = "data/reports", stores_path: str = "data/stores.csv"
) -> str:
paths = sorted(Path(folder).glob("2024-*.csv"))
with ThreadPoolExecutor(max_workers=len(paths)) as pool: # I/O-bound: threads
files = list(pool.map(slow.read_report, paths)) # keeps the month order
lines = [line for file in files for line in file]
with open(stores_path, newline="", encoding="utf-8") as f:
city_of = {row["store_id"]: row["city"] for row in csv.DictReader(f)}
revenue_by_city: dict[str, float] = {}
by_category: dict[str, list[float]] = {}
for line in lines:
city = city_of[line["store_id"]] # O(1) instead of a scan
revenue = float(line["revenue"])
revenue_by_city[city] = revenue_by_city.get(city, 0.0) + revenue
by_category.setdefault(line["category"], []).append(revenue)
by_category = dict(sorted(by_category.items()))
with ProcessPoolExecutor(max_workers=len(by_category)) as pool: # CPU-bound
intervals = list(pool.map(bootstrap_ci, by_category.values()))
return slow.format_report(lines, revenue_by_city, by_category, intervals)
def profile_slow() -> None:
"""Call counts of the slow version: they show where the time goes."""
with cProfile.Profile() as profiler:
slow.build_report()
funcs = pstats.Stats(profiler).get_stats_profile().func_profiles
names = ["read_report", "<built-in method time.sleep>", "find_city",
"bootstrap_ci", "mean"] # fmt: skip
print("Slow version, call counts:")
for name in names:
print(f" {name:<30}{funcs[name].ncalls:>8}")
def main() -> None:
profile_slow()
start = time.perf_counter()
before = slow.build_report()
slow_s = time.perf_counter() - start
start = time.perf_counter()
after = build_report()
fast_s = time.perf_counter() - start
print(after)
print("Same report:", after == before)
print("Speed-up at least 3x:", slow_s / fast_s >= 3)
assert after == before
if __name__ == "__main__":
main()
Output
Slow version, call counts:
read_report 6
<built-in method time.sleep> 6
find_city 297
bootstrap_ci 6
mean 60000
Nightly sales report, 2024-01 to 2024-06
Lines: 297 Revenue: 57,266.39
Top cities: Seattle 10,532.74, Houston 9,789.25, Philadelphia 5,995.64
Category lines mean 95% CI of the mean
Beauty 44 60.98 44.59 to 81.46
Books 34 35.63 27.54 to 45.21
Clothing 54 72.60 54.73 to 91.87
Electronics 67 479.84 343.33 to 635.17
Home 39 188.30 158.19 to 219.02
Sports 59 168.79 133.18 to 214.92
Same report: True
Speed-up at least 3x: True

Run it from the project folder, next to nightly_slow.py and data/:

Terminal
python nightly_fast.py

How it works:

  1. Profile first. profile_slow() shows the call counts that explain the time: 6 sleeps of 0.2 seconds (the drive) and 60,000 calls of statistics.mean (the CPU). find_city runs 297 times, a small cost, fixed anyway because it grows with the data.
  2. Threads for the waits. The six read_report calls run on six threads. Each thread releases the GIL while it sleeps, so the six waits overlap: 0.2 seconds instead of 1.2. pool.map returns the files in month order, so every later sum adds the same numbers in the same order.
  3. A dict index. city_of is built once from stores.csv. Each line then needs one O(1)O(1) lookup instead of a scan.
  4. Processes for the computation. The bootstrap is pure Python and CPU-bound, so threads would not help. A process pool runs the six categories on separate cores. bootstrap_ci is a top-level function in nightly_fast.py, so the workers can import it, and the main guard keeps them from running main() themselves.
  5. A faster mean. sum(sample) / n is many times faster than the exact statistics.mean. The seeds and draws are unchanged, so the intervals agree to every printed digit.
  6. Proof. The script compares the full report text with ==. The speed-up check has a wide margin: on a laptop, the fast version takes about 0.3 seconds against about 2.2.

Alternative: asyncio with asyncio.to_thread(slow.read_report, path) for the files works as well as the thread pool here. For the bootstrap, ProcessPoolExecutor.map could also be replaced by loop.run_in_executor(process_pool, ...) inside the same async program. Choose one style per program: a plain script with two executors, as here, is the simplest.