Account for Concurrency and Transfer Overhead
Core idea
Scheduling, synchronization, worker creation and data transfer cost time. Small tasks may cost more to dispatch than to execute. Process pools also serialize arguments and results; chunking can reduce dispatch frequency but can increase latency or imbalance. Compare sequential and concurrent runs with the same input and result, including startup if it matters to your service.
from concurrent.futures import ThreadPoolExecutordef square(n): return n*nvalues = list(range(8))serial = list(map(square, values))with ThreadPoolExecutor(max_workers=2) as pool: parallel = list(pool.map(square, values))print(serial == parallel, len(parallel))Both paths preserve order and results. This small CPU task provides no evidence of acceleration.
Expected output:
True 8Inspect serialized batch boundaries
from itertools import batchedimport picklevalues = tuple(range(12))chunks = list(batched(values, 4))encoded = [pickle.dumps(chunk) for chunk in chunks]print(len(chunks), sum(len(chunk) for chunk in chunks))print(all(isinstance(data, bytes) for data in encoded))Three locally serialized batches cover the same twelve items. Payload encoding is only one part of process transfer overhead; no untrusted data is deserialized.
Expected output:
3 12TrueCommon mistake
Do not infer speed from worker count or assume ThreadPoolExecutor.map chunksize reduces thread dispatch: chunksize affects process pools, not thread pools. Benchmark with representative task sizes and bounded resources.
Practice
Compare serial and thread-pool versions of a fixed workload at two sizes. Record setup and total time separately, verify outputs and explain why overhead may dominate at small sizes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency overhead
Check your understanding of concurrency overhead.
What is printed?
from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(max_workers=2) as p: print(list(p.map(abs,[-2,-1,0])))What is printed?
from itertools import batchedprint(len(list(batched(range(9),4))))Why might batching improve process-pool throughput?
When can scheduling overhead dominate?