Sub topic 13
Performance trade-offs and choosing between threads and processes
This chapter assumes you have run the earlier examples on a free-threaded build, and that you know the threading, concurrent.futures and multiprocessing basics. Removing the GIL does not make every program faster. This chapter covers what free-threading costs, where it pays off, and how to choose between threads and processes by measuring.
What free-threading costs
The GIL made many operations cheap because only one thread could touch an object at a time. Without it, the interpreter needs other mechanisms to keep objects consistent. Those mechanisms have a price, which falls into three groups.
- Single-thread speed. Reference counting, per-object locking and changes to the specializing interpreter add work to code that never creates a second thread. In Python 3.13, where the free-threaded build is experimental, the slowdown on single-threaded benchmarks was often large. In 3.14 the specializing adaptive interpreter works in the free-threaded build, and the gap is much smaller. The exact figure depends on the workload, so measure your own code.
- Memory. Objects carry extra header data for the new reference counting scheme. The allocator is also different (the Under the hood chapter covers both). Memory use usually rises a little for object-heavy programs.
- Contention. Threads that update the same object, such as a shared
dictorlist, now compete for that object's internal lock. Many threads hitting one container can run slower than a single thread would.
Free-threading buys you parallel execution of Python bytecode across cores. It is worth paying for only if your program can use that parallelism.
Where threads gain and where they do not
Different workloads respond differently to the GIL being removed.
| Workload | Standard build with threads | Free-threaded build with threads |
|---|---|---|
| Pure-Python CPU-bound work | No speedup, one thread runs at a time | Scales with cores, up to the core count |
| I/O-bound work (network, disk) | Good, threads release the GIL while waiting | Good, with little change |
| Calls into C code that already releases the GIL (NumPy, hashing, compression) | Good | Good, with little change |
| Many threads updating one shared object | Serialized by the GIL | Serialized by object locks or your own lock |
| Single-threaded script | Fastest | Somewhat slower |
I/O-bound programs gain almost nothing from free-threading. They already overlap their waiting under the GIL, so the move only adds the single-thread overhead. The clear winner is pure-Python CPU-bound work that splits into independent pieces.
Measuring instead of guessing
The script below runs the same CPU-bound job serially, on threads and on processes. Run it on a standard build and on a free-threaded build to compare.
import sys
import sysconfig
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_primes(limit):
return sum(1 for n in range(limit) if is_prime(n))
def run_serial(jobs):
return [count_primes(j) for j in jobs]
def run_pool(executor_cls, jobs, workers):
with executor_cls(max_workers=workers) as pool:
return list(pool.map(count_primes, jobs))
def timed(label, func, *args):
start = time.perf_counter()
result = func(*args)
elapsed = time.perf_counter() - start
print(f"{label:<10} {elapsed:6.2f} s {result}")
if __name__ == "__main__":
free = sysconfig.get_config_var("Py_GIL_DISABLED")
gil = sys._is_gil_enabled()
print(f"free-threaded build: {free}, GIL enabled: {gil}")
jobs = [200_000] * 4
timed("serial", run_serial, jobs)
timed("threads", run_pool, ThreadPoolExecutor, jobs, 4)
timed("processes", run_pool, ProcessPoolExecutor, jobs, 4)Typical results on a machine with at least four free cores:
- Standard build:
threadstakes about as long asserial, andprocessesis close to four times faster. - Free-threaded build with the GIL off:
threadsandprocessesboth come close to four times faster thanserial. Threads may be slightly ahead because they skip process startup. - Free-threaded build with
PYTHON_GIL=1:threadsbehaves like the standard build again, andserialis a bit slower than on the standard build because of the extra overhead.
Run the benchmark several times and use a job large enough to take a second or more. Short jobs mostly measure process startup and thread creation.
What processes still do better
Processes were the standard answer to CPU-bound Python before free-threading, and they keep real advantages.
- Isolation. A crash, a memory leak or a corrupted object in one worker does not affect the others. Threads share one address space, so a bug in one thread can bring the whole program down.
- No data races by construction. Each process has its own objects. You cannot forget a lock on state you never share.
- Works on any build. Processes need no special interpreter and no special extension builds.
- Scaling beyond one machine. The process model carries over to job queues and clusters. Threads do not.
What processes cost
- Startup time. Starting a process takes longer than starting a thread. With the
spawnstart method, each worker also re-imports your modules. - Serialization. Arguments and results move between processes by pickling. Large arguments, such as a big list or array, can cost more to send than the work costs to do.
- Memory. Each process holds its own copy of the interpreter and of any data it loads. With the
forkstart method, pages are shared at first but can be copied as reference counts change. - Shared state is awkward. Sharing mutable data needs
multiprocessing.shared_memory, a manager process or an external store. Threads can just read the same object.
Threads win when the workers need to read a large shared structure, such as a big lookup table, a model or a graph, or when tasks are small and numerous. Sending the same 2 GB table to each of eight processes is a real cost. Eight threads reading one copy is not.
Contention and false hope
Free-threading removes the global lock, but it does not remove every point where threads wait on each other. Suppose four threads all append to one list under a threading.Lock, as in this chapter's earlier counter example. The lock serializes the critical section, and the parallel speedup shrinks as more of the time is spent inside it.
A rough guide:
- Keep the work done while holding a lock short.
- Prefer per-thread results that you combine at the end over one shared accumulator.
- Avoid hot shared objects, such as a global counter touched on every iteration.
Here is the pattern with per-thread results. Each thread counts into its own local variable, and the main thread adds up the totals, so no lock is needed during the loop.
from concurrent.futures import ThreadPoolExecutor
def count_chunk(bounds):
start, stop = bounds
total = 0
for n in range(start, stop):
if n % 3 == 0:
total += 1
return total
if __name__ == "__main__":
chunks = [(i * 250_000, (i + 1) * 250_000) for i in range(4)]
with ThreadPoolExecutor(max_workers=4) as pool:
print(sum(pool.map(count_chunk, chunks))) # 333334Compare this with a version where all four threads call with lock: counter += 1 on every iteration. The first version scales with cores on a free-threaded build, and the second mostly waits.
Deciding in practice
Work through the decision in this order.
Three further checks come before you commit.
- Dependencies. If a C extension you rely on has not declared free-threaded support, importing it can re-enable the GIL for the whole process (the extension chapter covers this). In that case your threads lose their parallelism with no error. Check
sys._is_gil_enabled()after your imports, not just at startup. - Deployment. A free-threaded interpreter is a separate build, such as
python3.13t. Your container images, CI and packaging must install it, and your wheels must exist for it. - Single-thread paths. If your application is mostly single-threaded with an occasional burst of parallel work, the overhead on the common path may outweigh the gain. Processes started only for the bursts may be a better fit.
Summary of the trade-offs
| Factor | Threads (free-threaded) | Processes |
|---|---|---|
| CPU parallelism for pure Python | Yes | Yes |
| Startup cost per worker | Low | Higher |
| Sharing large data | Direct, cheap | Pickling or shared memory |
| Fault isolation | None | Strong |
| Data race risk | Yes, you must lock | Only on explicit shared state |
| Single-thread overhead | Some | None |
| Dependency requirements | Free-threaded build and compatible extensions | Any build |
Exercise
A service loads a 3 GB read-only index into memory and then answers CPU-heavy queries in pure Python using eight workers. It runs on a standard build today with ProcessPoolExecutor. Under what conditions would you move it to threads on a free-threaded build, and what would you check first?
Show answer
Threads suit this service because eight processes each need access to the 3 GB index, which means large memory use or heavy pickling, while eight threads can read one copy. Before moving, check three things: that a free-threaded interpreter and wheels exist for every dependency, that sys._is_gil_enabled() is still False after all imports so no extension has re-enabled the GIL, and that a benchmark on real queries shows a speedup large enough to offset the single-thread overhead. If the service also needs crash isolation between queries, or a dependency forces the GIL back on, keep the processes.
Exercise
You run the benchmark from this chapter on a free-threaded build and threads takes as long as serial. Name two likely causes and how you would confirm each.
Show answer
First, the GIL may be enabled, either through PYTHON_GIL=1 or because an imported extension re-enabled it. Confirm by printing sys._is_gil_enabled() after the imports. Second, the machine may not have four free cores, or the job may be too short to outweigh thread startup. Confirm by checking the core count with os.cpu_count(), watching CPU usage during the run, and increasing the job size. Contention on a shared lock inside the work function is a third possibility.