Distinguish I/O Wait from CPU Work
Core idea
A CPU-bound workload spends most of its time computing; an I/O-bound workload spends substantial time waiting for external data. Measure elapsed and CPU time and inspect relevant operations before choosing an optimization. Reduce unnecessary computation or use appropriate algorithms for CPU work; batch requests or overlap independent waiting for I/O. Local examples model work without depending on a live service.
calls = 0def compute(n): global calls calls += 1 return n*nvalues = [2, 3, 2, 3]lookup = {n: compute(n) for n in dict.fromkeys(values)}print([lookup[n] for n in values], calls)Computing each distinct value once reduces calls for this repeated workload; the dictionary consumes memory.
Expected output:
[4, 9, 4, 9] 2Model batched service calls
calls = []def fetch_many(ids): calls.append(tuple(ids)) return [i*10 for i in ids]ids = [1, 2, 3]answer = fetch_many(ids)print(answer, len(calls))The synthetic adapter handles three identifiers in one request. Actual latency and limits need real service measurements.
Expected output:
[10, 20, 30] 1Common mistake
Do not assume a thread pool speeds every CPU loop on a GIL-enabled CPython build. Also do not batch arbitrarily large requests; external services impose limits and error contracts.
Practice
Instrument an existing local data-processing function with elapsed time and CPU time. Count calls to its dependency and identify whether an algorithmic or batching change should be tested.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O and CPU bottlenecks
Check your understanding of i/o and cpu bottlenecks.
What is printed?
xs=[1,1,2,2]print(len(set(xs)))What is printed?
calls=[]def fetch(x): calls.append(x); return xprint(fetch([1,2,3]),len(calls))What is a likely I/O bottleneck?
What should guide optimization choice?