Part 14 / Topic 11 of 11
Putting it together: find the slow function
Real-world example: a shop's nightly sales report (examples/sales_report.py) takes too long. It builds totals per city and a list of repeat customers from 10,000 orders. Somewhere there is a hidden slow function.
The investigation in examples/08_find_the_slow_function.py follows the "measure, don't guess" steps:
- Time the whole report with
perf_counter. - Profile it with
cProfileand read the top lines withpstats. - Fix only the function the profile points at.
- Check the answer is identical, then time it again.
The profile points straight at repeat_customers:
(timings vary)
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.333 0.333 sales_report.py:47(build_report)
1 0.327 0.327 0.329 0.329 sales_report.py:35(repeat_customers)
1 0.002 0.002 0.003 0.003 sales_report.py:28(total_by_city)
Its tottime is almost all of the time. in on a list is not a function call, so the cost shows up inside the function itself. The culprit:
def repeat_customers(orders):
seen, repeats = [], []
for order in orders:
name = order["customer"]
if name in seen and name not in repeats: # scans two growing lists, every time
repeats.append(name)
seen.append(name)
return sorted(repeats)
The fix counts every customer once with Counter, a dict, so each lookup is instant:
from collections import Counter
def repeat_customers_fast(orders):
counts = Counter(order["customer"] for order in orders)
return sorted(name for name, times in counts.items() if times >= 2)
Output (timings vary):
== 1. The report (it feels slow) ==
Orders: 10,000
Repeat customers: 2,987
Pune ₹5,275,002
Chennai ₹5,212,309
Kolkata ₹5,130,011
Delhi ₹5,112,731
Jaipur ₹4,781,319
Took 0.301 s (varies)
...
== 3. Fix only repeat_customers, then check ==
Same report: True
== 4. Before and after (varies) ==
Before: 301.3 ms
After : 3.1 ms
About 98x faster
One small change in the right place, found by measuring, made the report about 100 times faster. total_by_city was never the problem, so it was left alone.
Full programs: examples/sales_report.py and examples/08_find_the_slow_function.py.
Done here? The practice set for Part 14 — 8 exercises with solutions — is on the part page.