17/34
Part 5 of 8 · Threads or processesLearn and do

About one process per core for computing, and more threads for waiting

For computing, use about one process per core. The same eight computing tables took 0.780 s on 1 process, 0.428 s on 2 and 0.261 s on 4. Past the number of cores, extra processes take turns, and they add start-up and memory.

os.cpu_count() gives the number of logical CPUs. It printed 10 on this laptop. In Python 3.12, ProcessPoolExecutor() with no max_workers uses that number. Each worker is a whole Python process that holds its own copy of what you send it, so memory can set the limit before cores do.

For waiting, use more: enough to keep the waits overlapped. That's the number of calls you want to start per second times how long each one waits, which is Little's law. For 50 reads a second that each wait 0.2 s, that's about 10 threads.

ThreadPoolExecutor() defaults to min(32, os.cpu_count() + 4) in 3.12. The docs give the plus 4 as a way to keep at least 5 workers for I/O-bound tasks. Since 3.13, both pools count os.process_cpu_count() instead of os.cpu_count(): the CPUs this process is allowed to run on, which can be fewer than the machine has.

In the editor, write process_count(cpus, memory_gb, per_worker_gb), one process per CPU unless memory runs out first, and thread_count(per_second, wait_seconds), by Little's law.