0Pricing
R Academy · Lesson

parallel Package and detectCores()

Launch forked or socket clusters and distribute work across CPU cores.

Why Parallel Computing?

Modern computers have multiple CPU cores. By default, R runs on a single core, leaving the rest idle. The parallel package (built into R) lets you harness all cores to speed up repetitive computations.

# Check how many cores your machine has
library(parallel)

total_cores <- detectCores()
logical_cores <- detectCores(logical = TRUE)
physical_cores <- detectCores(logical = FALSE)

cat('Total logical cores:', total_cores, '
')
cat('Physical cores:', physical_cores, '
')

makeCluster and stopCluster

makeCluster(n) spawns n worker processes. Always call stopCluster(cl) when done to free resources. A common convention is to use detectCores() - 1 to leave one core for the OS.

library(parallel)

# Spawn workers (leave 1 core for system)
n_cores <- detectCores() - 1
cl <- makeCluster(n_cores)

cat('Cluster created with', n_cores, 'workers\n')

# Always clean up!
stopCluster(cl)
cat('Cluster stopped.\n')

All lessons in this course

  1. parallel Package and detectCores()
  2. The future Framework
  3. furrr: Parallel purrr Operations
  4. Debugging and Load Balancing Parallel Code
← Back to R Academy