Imagine handing another process a 4 MiB byte string just to look up byte 31. Which takes longer, reading the byte or getting the input to the process that reads it? When I was considering a pool for a web service, I first asked, “ProcessPoolExecutor's communication cost is lower than message queues right?” Then I noticed another comparison mattered more: “when Pickling/Serialization's cpu cost is higher than the task it will not be ideal rigt?”
What does a local pool save?
In a local ProcessPoolExecutor I submit a function and its arguments to a pool of reusable child processes. With a separate task queue, the service sends a message to a broker such as Redis or RabbitMQ. A worker then takes the job from there. A local pool saves the trip through a broker. A broker can also deliver work to another machine or, with the appropriate configuration, retain pending jobs across restarts. The latency depends on where the data goes, how it is encoded and whether it has to be written to durable storage.12
There is a cheaper starting point for a byte lookup. The caller already has the data and could just index it. How much would I pay to get that same answer back from a child?
Where does the time go when all I want is 32 byte lookups?
For ordinary function arguments, Python uses pickle to serialize objects into bytes that can cross a process boundary. The receiver deserializes the bytes into objects. Results make the return trip. Elapsed time from submission to result also includes queueing, waking a worker and delivering its reply. I warmed up one worker so that process startup and multicore speedup would both stay out of this comparison.1
I used the same immutable 4 MiB input and read 32 positions. Each version returned the integers 0 through 31. These are median wall-clock times for the whole batch over five runs on Linux x86-64 with CPython 3.12.3 and the spawn start method. For the last row the data had already been loaded into the child.
| How the 32 lookups run | What travels to the calculation | Time on this machine |
|---|---|---|
| Index directly in the caller | The bytes are already there | About 0.001 ms |
| Submit 32 individual jobs with ordinary arguments | 4 MiB and an index on every submission | 223 ms |
| Submit one batch | 4 MiB once, with 32 indices | 6.53 ms |
| Keep the data in the worker, submit 32 jobs | One index per job | 2.20 ms |
A separate control took a median of 2.36 ms for one pickle.dumps followed by pickle.loads on the block in the same process. That isolates local encoding and decoding. It measures elapsed time, so it cannot tell us the sum of CPU time consumed by two processes. Even that one round trip through pickle took longer than reading all 32 positions locally.
Should I batch the jobs or send only the indices?
If several calculations need the same input once, filter the data where it lives or send one job containing all the indices. Larger batches spread the fixed cost of dispatch across more work. A very large batch can keep a short job waiting or leave other workers idle.
If many successive jobs need the same input, load it once in each worker's initializer and send only an index thereafter. Budget for startup and one copy per process. If the data changes, decide how a worker will learn which version it should read.1
Would threads without the GIL solve the problem?
My next question was “so threads with no GIL and use shared memory will be more optimal right?” Threads in one process can already read the same bytes object by reference. They can avoid repeatedly copying 4 MiB even in conventional CPython. Dispatching a one-byte lookup to a thread still takes time. Direct indexing avoids that cost too.
The global interpreter lock (GIL) matters when substantial computation follows the lookup. In a conventional CPython interpreter it limits how many threads can execute Python bytecode at once. Native code that releases the GIL, or the optional free-threaded build introduced in Python 3.13, can allow suitable calculations to use several cores. Sharing immutable input is straightforward. If two threads also update a running total, measure the cost of coordinating their writes.3
Processes can explicitly share memory as well. For example, put image pixels in a multiprocessing.shared_memory segment and give each process the segment name and its assigned row numbers. The processes need to agree on layout, who writes which rows and who releases the segment. The last row of the table used a private copy in the worker. That alone was enough to eliminate repeated transmission.4
How can I reproduce the comparison with my own input?
Save this standard-library script as bench.py and run python bench.py. The child must be able to import the worker functions, so they are defined at module scope and the pool is created under the main guard.1
import pickle
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import get_context
from statistics import median
from time import perf_counter
def read_at(data, offset):
return data[offset]
def read_batch(data, offsets):
return [data[i] for i in offsets]
def remember(data):
global worker_data
worker_data = data
def read_local(offset):
return worker_data[offset]
def measure(run, expected):
samples = []
for _ in range(5):
start = perf_counter()
result = run()
assert result == expected
samples.append((perf_counter() - start) * 1000)
return median(samples)
if __name__ == "__main__":
data = bytes(range(256)) * 16384 # 4 MiB
offsets = list(range(32))
expected = read_batch(data, offsets)
print("direct", measure(lambda: read_batch(data, offsets), expected))
print("pickle one", measure(
lambda: pickle.loads(pickle.dumps(data, protocol=4))[31], 31))
with ProcessPoolExecutor(max_workers=1, mp_context=get_context("spawn"),
initializer=remember, initargs=(data,)) as pool:
pool.submit(read_local, 0).result() # Warm up the pool to exclude startup.
def separate():
jobs = [pool.submit(read_at, data, i) for i in offsets]
return [job.result() for job in jobs]
print("32 sends", measure(separate, expected))
print("one batch", measure(
lambda: pool.submit(read_batch, data, offsets).result(), expected))
print("resident", measure(
lambda: list(pool.map(read_local, offsets, chunksize=1)), expected))
For a real report I would run the calculation directly, then keep the same input and output sizes while giving the worker the smallest possible job, then time the actual batch at the intended concurrency. Record both throughput and how long one job waits. This experiment measured an extremely small calculation and did not benchmark an external queue. If my objective is to keep a web service responsive, I also need to measure when a second, lightweight request gets its answer.
Footnotes
-
Python Software Foundation. (n.d.). concurrent.futures — Launching parallel tasks. Python 3.12 Documentation. ProcessPoolExecutor · The chunksize argument to Executor.map. ↩ ↩2 ↩3 ↩4
-
Celery contributors. (n.d.). Introduction to Celery. Celery Documentation. What’s a task queue?. ↩
-
Python Software Foundation. (2024). Python experimental support for free threading. Python 3.13 Documentation. Free-threaded build. ↩
-
Python Software Foundation. (n.d.). multiprocessing.shared_memory. Python 3.12 Documentation. SharedMemory. ↩