Skip to content
fn

parallel_chunk_count

int parallel_chunk_count(int n, int grain)

Call fn(begin, end) over [0, n) in contiguous chunks, in parallel.

Parameters

nstd::size_t
Iteration count.
grainstd::size_t
Smallest chunk worth handing to another core. Below two of them the loop runs inline on the caller: dispatching costs a few microseconds, which a small loop never earns back.
fnF
void(std::size_t begin, std::size_t end). Must not throw — an exception cannot cross a libdispatch worker — and must write only what its own range owns.

Notes

Chunks are n * i / chunks to n * (i + 1) / chunks, so they differ in size by at most one iteration and together cover [0, n) exactly.

There are up to four chunks per worker, not one. Apple silicon mixes performance and efficiency cores — an M1 Pro is 6 + 2 — and an efficiency core runs this kind of loop about three times slower. With one chunk per core, the wall time was the efficiency cores' share: the exact GELU on 524k elements took 0.40 ms where the performance cores alone finish in half that. Smaller chunks let libdispatch hand the fast cores more of them. A chunk is never smaller than grain.