12.4 SIMD, R Vectorization, and Threads
The word vectorization appears in three different contexts and means three different things. R programmers and data scientists conflate them. Understanding the distinction prevents misconceptions about performance and why parallelism does not always help.
12.4.1 Three meanings of vectorization
R vectorized functions are functions that work on entire arrays without explicit loops. In R, x + y adds two numeric vectors element-by-element. The R code is vectorized syntax because there is no for loop visible.
SIMD (single instruction multiple data) is a CPU instruction that operates on multiple values at once. One instruction executes once, on one core, and produces several results.
Multithreading runs the same operation on different data across multiple processor cores simultaneously. Work splits among cores.
These three things are different. Only the third is parallelism in this book’s sense, work running on several cores at once. Users often mistake R vectorization or SIMD for multicore parallelism and assume vectorized code will spread to more cores on its own.
12.4.2 R vectorized syntax is a C loop, not parallelism
When you write x + y in R on two numeric vectors of 1000 elements, R calls a compiled C function. The C function contains a tight loop that adds all 1000 pairs. The loop is in C, fast, and uses cache well. The loop runs on one core.
R’s arithmetic operators dispatch to C loops compiled into R itself. For two double vectors of equal length, x + y runs the loop da[i] = dx[i] + dy[i] in real_binary() in src/main/arithmetic.c, in chunks of ten million elements with an interrupt check between chunks. The loop runs on one core and contains no SIMD intrinsics.
The loop is not automatically parallel, and adding cores does not speed it up. To use four cores on x + y, you must split the vectors, run the operation on each split independently, and merge the results. That is explicit parallelism, not vectorization.
12.4.3 SIMD instructions execute on one core
SIMD instructions run on a single CPU core. Modern x86 cores have SIMD registers of three widths: SSE (128-bit), AVX (256-bit) and AVX-512 (512-bit). One AVX register holds eight 32-bit floats or four 64-bit doubles, and an R numeric vector is made of doubles, so one AVX add handles four of its elements. That is still one instruction on one core.
A compiler that sees a simple loop over arrays can turn it into SIMD instructions on its own, which is called auto-vectorization. With AVX, the loop then needs a quarter as many add instructions for doubles. Whether it runs four times faster depends on whether the data arrives fast enough: once the vectors are larger than the caches, memory bandwidth sets the speed, and the number of add instructions was never the bottleneck.
Adding a second core does not make one SIMD instruction faster. Each core has its own SIMD units, so two cores running x + y on different vectors each get the SIMD gain. But if one core runs a single x + y operation, a second core cannot speed it up.
12.4.4 The speed of R’s x + y
When you run x + y on a numeric vector in R, several things make it fast:
- C implementation: The operation is compiled C, not interpreted R.
- Branch prediction: For two double vectors of equal length, the inner loop has no data-dependent branches, so the CPU predicts its loop branches almost perfectly.
- Cache locality: The loop accesses memory sequentially. Cache lines load efficiently.
- Possibly SIMD: R’s source contains no SIMD intrinsics for this loop, so whether it runs as SIMD depends on the compiler and the flags R was built with.
None of these uses a second core.
Matrix products are where R does reach SIMD code, through BLAS. %*%, crossprod() and tcrossprod() call the BLAS library R is linked to, except when the inputs may contain NaN or Inf (see matprod in ?options). The reference BLAS that ships with R is plain Fortran (src/extra/blas/blas.f). Optimized libraries such as OpenBLAS and Intel’s MKL use hand-tuned SIMD kernels and several threads, so swapping one in changes the speed of linear algebra without any change to the R code.
12.4.5 Using multiple cores on a numeric operation
Using four cores on a numeric operation requires explicit work. You must split the input, run the operation on each split in parallel, and merge results.
x <- runif(1e6)
y <- runif(1e6)
# Vectorized on one core (no parallelism)
result <- x + y
# Explicit parallelism on four cores (mcmapply forks, so Unix-alikes only)
chunk <- cut(seq_along(x), 4, labels = FALSE)
parts <- parallel::mcmapply(function(a, b) a + b,
split(x, chunk), split(y, chunk),
SIMPLIFY = FALSE, mc.cores = 4)
result2 <- unsplit(parts, chunk)
identical(result, result2) # TRUER packages like data.table, arrow, and polars run some operations across several threads internally. But the + operator itself is not parallel. The parallelism is in how you structure the data and distribute work.
12.4.6 The misunderstanding and its cost
Many R users believe that vectorized operations are automatically parallel or will benefit from parallelization. This leads to design decisions that fail. A user writes vectorized code expecting it to scale to 32 cores. It does not. The vectorization is already compiled to a sequential C loop.
Adding parallelism to an already-vectorized operation requires changing the algorithm, and with process workers the input size alone does not rescue it. For x + y, copying the inputs to the workers and the results back grows with the vector exactly as the addition does, so the copying never shrinks relative to the work. Process workers pay off when each element costs much more to compute than to copy.
12.4.7 Worked example: when not to parallelize
On my machine (Windows 11, R 4.6.1, 8 physical cores), x + y on two vectors of a million doubles takes about 1.4 milliseconds.
Parallel version: split both vectors into 8 chunks, add the chunk pairs on an 8-worker PSOCK cluster with clusterMap(), and join the results with unsplit(). This takes about 87 milliseconds, roughly 60 times as long as the serial addition. Building the chunk index with cut() and splitting the two vectors takes about 41 milliseconds of that on its own. The rest covers sending 16 MB of chunks to the workers, the additions themselves, and returning and joining 8 MB of results.
Serial version: result <- x + y, about 1.4 milliseconds.
The arithmetic was never the slow part. Do not parallelize operations that are already fast and memory-intensive: the cost of moving the data dominates the cost of computing on it.
12.4.8 When parallelization does help with array operations
Parallelization of array operations makes sense in specific scenarios:
Very large arrays, with threads: In one address space nothing is copied. Several threads can each add part of the vectors and together draw more memory bandwidth than one core can on its own, up to the machine’s ceiling (see The Cache Hierarchy and Memory Bandwidth).
Complex operations: Elementwise addition is cheap. Elementwise matrix operations, statistical calculations, or transformations are more expensive. Parallelization helps when the operation is not bandwidth-bound.
Out-of-core processing: When the data does not fit in RAM, you must read from disk or network. Parallelism can hide this latency. While one worker waits for disk, others compute.
Reduction operations: Some operations must combine results from all elements. Computing a sum, mean, or finding a max requires a reduction. Each thread can reduce its own part and the partial results are combined at the end, so a reduction splits across cores much as an elementwise operation does, with the same bandwidth limit.
12.4.9 Measuring when to parallelize
Do not parallelize x + y. It is already optimized. Do measure:
- Execution time: How long does the operation take on one core?
- Communication cost: How long to split data, send to workers, and merge?
- Breakeven point: At what input size is parallelism faster?
If communication cost is 100 milliseconds and the operation takes 50 milliseconds, do not parallelize. If the operation takes 10 seconds, parallelization may pay off.
12.4.10 Failure modes
A user times x + y on two vectors of a billion doubles, 8 GB each, and it takes a few seconds. The user expects eight cores to cut that by eight and parallelizes it with an R worker pool. The parallel version is barely faster, or slower, because every worker must first receive its share of 16 GB and then send back its part of 8 GB. The user concludes parallelism is slow and gives up.
Moving 24 GB through memory costs more than the addition, and process workers add copies on top of it. What helps is avoiding the copies: threads that share one address space, a library that computes in place, or not building the full vectors at all.
Another user builds a machine learning pipeline that calls x + y thousands of times per second. The pipeline runs slow. The user parallelizes each addition. The parallel versions run slower, because each call now pays to dispatch work to a worker and collect the result. The fix is to batch operations so that one dispatch covers many of them.
A researcher claims that parallelizing vectorized R code achieved 10x speedup on 10 cores. That is plausible for an expensive operation on large data, but the claim means little until it states the single-core baseline, the data size, and whether the time spent moving data to and from the workers was included.
Further reading
- Drepper, U. (2007). What Every Programmer Should Know About Memory <https://www.akkadia.org/drepper/cpumemory.pdf>. Section 6.2 vectorizes a matrix multiplication with SSE2 and shows the effect of cache behavior on it.
- Intel, Intel Intrinsics Guide <https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html>, the reference for x86 SIMD instructions.
- R source,
src/main/arithmetic.c<https://svn.r-project.org/R/tags/R-4-6-1/src/main/arithmetic.c> in R 4.6.1, wherereal_binary()holds the arithmetic loops. - Fog, A. Optimizing software in C++ <https://www.agner.org/optimize/optimizing_cpp.pdf>. Chapter 13, “Using vector operations”, covers SIMD and automatic vectorization by compilers.