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

On standard CPython, threads speed up waiting, and processes speed up Python computing

Measured: 4 threads did nothing for Python computing and cut the waiting to a quarter

Two kinds of work, eight tables of 100 rows by 100 columns, three ways each:

  • Computing. Every value goes through heavy, 200 rounds of Python arithmetic. It stands in for real work on each value, like parsing. Then a clip.
  • Waiting. Each table first sleeps 0.1 s. It stands in for a read from a slow disk or the network. Then a cheap clip.
# in tables.py, next to this lesson's other functions
def heavy(value):
    for _ in range(200):
        value = (value * 31 + 7) % 1_000_003
    return value


def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32

The script runs each kind of work in a plain loop, on 4 threads and on 4 processes:

import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

from tables import apply, heavy


def compute(table):
    return apply(table, [("map", heavy), ("clip", 0, 500_000)])


def wait(table):
    time.sleep(0.1)
    return apply(table, [("clip", 0, 500)])


if __name__ == "__main__":
    tables = [[[(k * 7 + i * 100 + j) % 997 for j in range(100)] for i in range(100)] for k in range(8)]
    for work in (compute, wait):
        start = time.perf_counter()
        loop = [work(t) for t in tables]
        print(work.__name__, "loop", time.perf_counter() - start)
        for Pool in (ThreadPoolExecutor, ProcessPoolExecutor):
            start = time.perf_counter()
            with Pool(max_workers=4) as pool:
                assert list(pool.map(work, tables, timeout=30)) == loop
            print(work.__name__, Pool.__name__, time.perf_counter() - start)

Medians of 3 runs of that script, Python 3.12, on a 10-core laptop, pool start-up included:

Predict

Each of eight tables first waits 0.1 s. A plain loop took 0.86 s. About how long on 4 threads?

Pick an answer above to see the rest