Full answer
python
import cProfile, pstats, io
def slow_unique(items):
seen = []
for x in items:
if x not in seen:
seen.append(x)
return seen
def fast_unique(items):
return list(dict.fromkeys(items))
data = list(range(3000)) * 2
pr = cProfile.Profile()
pr.enable(); slow_unique(data); fast_unique(data); pr.disable()
stats = pstats.Stats(pr).sort_stats("cumulative")
rows = sorted(((v[3], k[2]) for k, v in stats.stats.items() if k[2] in ("slow_unique", "fast_unique")), reverse=True)
print("slowest first:", [name for _, name in rows])
print(slow_unique(data) == fast_unique(data))Output:
text
slowest first: ['slow_unique', 'fast_unique']
TrueThe profiler records cumulative time per function; the run prints only the ranking, not timings, so the result is stable. slow_unique dominates because x not in seen scans a growing list, making the function quadratic, while dict.fromkeys uses hashing and is linear. Both produce the same result, so the fix is safe. In real services, profile with production-like data, look at cumulative time first, and consider I/O waits, which profilers attribute to waiting functions rather than computation.
python
import cProfile, pstats, io
def slow_unique(items):
seen = []
for x in items:
if x not in seen:
seen.append(x)
return seen
def fast_unique(items):
return list(dict.fromkeys(items))
data = list(range(3000)) * 2
pr = cProfile.Profile()
pr.enable(); slow_unique(data); fast_unique(data); pr.disable()
stats = pstats.Stats(pr).sort_stats("cumulative")
rows = sorted(((v[3], k[2]) for k, v in stats.stats.items() if k[2] in ("slow_unique", "fast_unique")), reverse=True)
print("slowest first:", [name for _, name in rows])
print(slow_unique(data) == fast_unique(data))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Measure first
- timeit for snippets, cProfile for programs
- Sort by cumulative time
- Fix algorithms before micro-optimising
- Verify results stay the same
Common mistakes
- Optimising without profiling
- Micro-optimising code that is not the bottleneck
Follow-ups
- How does py-spy profile a running process?
- When does tracemalloc help?
Tips
- Show the before and after