Parallel reduction
Count primes below 2,000,000 with 4 workers.
What is measured
Counts primes below 2,000,000 by trial division (odd divisors up to the square root). Numbers are dealt out to 4 workers in an interleaved pattern (worker t takes n where n mod 4 = t) and the partial counts are summed.
Pseudocode
isPrime(n) = n >= 2 and no odd divisor d <= sqrt(n) divides n (n = 2 is prime, even n > 2 is not)
worker(t): # t = 0..3
count = 0
for n = t; n < 2,000,000; n += 4:
if isPrime(n): count++
return count
start 4 workers (threads / processes) running worker(0..3)
print sum of their countsReveals: Thread creation, scheduling and scaling on a 4-core runner.
Caveat: Thread count, scheduling and synchronisation matter. Python uses multiprocessing (processes) because of the GIL; Node uses worker_threads; Ruby and PHP also use separate processes. GitHub-hosted runners have 4 vCPUs (public repos) which are hyper-threads. Deno uses module Workers, Nim and Haskell native threads, F# threads; Lua, Perl and OCaml use forked processes, Elixir uses Task.async_stream.
Results (newest release of each language)
| Language / build | Time (× vs best) | |
|---|---|---|
| Go 1.27 · GOAMD64=v3 go build | 93.5 ms (1.00×) | |
| Go 1.27 · go builddefault | 98.1 ms (1.05×) | |
| C 16 · gcc -O3 -march=nativedefault | 105 ms (1.12×) | |
| C 16 · gcc -O3 | 106 ms (1.13×) | |
| C 16 · gcc -O2 | 106 ms (1.14×) | |
| Python 3.15 · python3default | 2.19 s (23.4×) |
Click a language to see the source code, build flags, every session and how the number was computed.