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.
Dataset
Section titled “Dataset”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: the nightly sales report, before any optimization.import csvimport randomimport statisticsimport timefrom pathlib import Path
NETWORK_DELAY = 0.2 # each file read waits this long for the network driveRESAMPLES = 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()Nightly sales report, 2024-01 to 2024-06Lines: 297 Revenue: 57,266.39Top cities: Seattle 10,532.74, Houston 9,789.25, Philadelphia 5,995.64Category lines mean 95% CI of the meanBeauty 44 60.98 44.59 to 81.46Books 34 35.63 27.54 to 45.21Clothing 54 72.60 54.73 to 91.87Electronics 67 479.84 343.33 to 635.17Home 39 188.30 158.19 to 219.02Sports 59 168.79 133.18 to 214.92Built in 2.21 sThe last line is the duration of one run on a laptop. Yours differs. Every other line must stay exactly the same after your changes.
Requirements
Section titled “Requirements”Write nightly_fast.py. It must:
- 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. - Profile the slow version with
cProfileand print the call counts of the functions that matter:read_report,time.sleep,find_city,bootstrap_ciandstatistics.mean. - Replace the store scan in
find_citywith a dict index that is built once. - Read the six files concurrently with a
ThreadPoolExecutor, in month order. - Compute the six bootstrap intervals in a
ProcessPoolExecutor, one task per category, with a faster mean thanstatistics.mean, and with the same random draws as the slow version. - Run as a script with
if __name__ == "__main__":, with every task function defined at the top level of a module. - Print
Same report: TrueandSpeed-up at least 3x: True, measured withtime.perf_counter().
Step plan
Section titled “Step plan”-
Measure the baseline. Run
nightly_slow.pytwice and note the time. On a laptop it takes a little over 2 seconds. -
Profile it. Wrap
slow.build_report()inwith cProfile.Profile() as profiler:. Printpstats.Stats(profiler).sort_stats("cumulative").print_stats(12)once to read the full table. Then print only the call counts you need fromget_stats_profile().func_profiles. -
Read the profile. Two things dominate.
time.sleepis called 6 times and accounts for about 1.2 seconds: the script waits for the drive, one file after the other.statistics.meanis called 60,000 times (6 categories × 10,000 resamples): that is the CPU cost.find_cityruns 297 times over 12 stores, which is cheap today but grows with the data. -
Fix the scan. Build
city_of = {store_id: city}once and look up each line in . -
Overlap the waits. Read the files with
ThreadPoolExecutor(max_workers=6)andpool.map(slow.read_report, paths).mapkeeps the month order, so the lines and every float sum come out in the same order as before. -
Parallelize the bootstrap. Write a top-level
bootstrap_cithat seedsrandom.Random(42)and draws exactly as the slow version, but computes each mean assum(sample) / n. Run it withProcessPoolExecutorandpool.mapover the categories. -
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: 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()Rubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- 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_workersfor the thread pool by measurement. - Replace the thread pool with asyncio: run each blocking
read_reportwithasyncio.to_thread()and gather the six reads. - Add a
--profilecommand-line flag withargparsethat prints the fullprint_stats(15)table of the slow version. - Move the bootstrap to NumPy:
rng.choice(values, size=(10_000, n)).mean(axis=1)withnp.random.default_rng(42). The intervals change (another random generator), so compare against a new baseline. Is the process pool still worth it? - Write a pytest test (module 14) that checks
build_report()of both versions on a small folder intmp_path, withNETWORK_DELAYset to 0 throughmonkeypatch.
Reference solution
Section titled “Reference solution”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: the same report, profiled, fixed and run concurrently.import cProfileimport csvimport pstatsimport randomimport timefrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutorfrom 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()Slow version, call counts: read_report 6 <built-in method time.sleep> 6 find_city 297 bootstrap_ci 6 mean 60000Nightly sales report, 2024-01 to 2024-06Lines: 297 Revenue: 57,266.39Top cities: Seattle 10,532.74, Houston 9,789.25, Philadelphia 5,995.64Category lines mean 95% CI of the meanBeauty 44 60.98 44.59 to 81.46Books 34 35.63 27.54 to 45.21Clothing 54 72.60 54.73 to 91.87Electronics 67 479.84 343.33 to 635.17Home 39 188.30 158.19 to 219.02Sports 59 168.79 133.18 to 214.92Same report: TrueSpeed-up at least 3x: TrueRun it from the project folder, next to nightly_slow.py and data/:
python nightly_fast.pyHow it works:
- Profile first.
profile_slow()shows the call counts that explain the time: 6 sleeps of 0.2 seconds (the drive) and 60,000 calls ofstatistics.mean(the CPU).find_cityruns 297 times, a small cost, fixed anyway because it grows with the data. - Threads for the waits. The six
read_reportcalls 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.mapreturns the files in month order, so every later sum adds the same numbers in the same order. - A dict index.
city_ofis built once fromstores.csv. Each line then needs one lookup instead of a scan. - 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_ciis a top-level function innightly_fast.py, so the workers can import it, and the main guard keeps them from runningmain()themselves. - A faster mean.
sum(sample) / nis many times faster than the exactstatistics.mean. The seeds and draws are unchanged, so the intervals agree to every printed digit. - 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.