Parallel Execution with parallel.parfor (Multi-core CPU)

Parallel execution is essential when you have compute-heavy workloads (simulation loops, Monte Carlo runs, parameter sweeps, batch processing, etc.). Instead of running tasks one-by-one, you can split the work across all available CPU cores, dramatically reducing total runtime.

This example uses parallel.parfor(...) to compute squares in parallel.


What this example demonstrates

  • Running a for-style loop in parallel using parallel.parfor

  • Automatically using all CPU cores via parallel.getProcessorsNum()

  • Collecting results back into a single array


JavaScript Example

// Parallel Execution

var computeSquare = (i) => i * i;

// Run parallel execution
var results = await parallel.parfor(
  0,                      // start
  20,                     // end
  1,                      // step
  parallel.getProcessorsNum(), // number of workers (CPU cores)
  {},                     // options
  undefined,              // (optional) shared data / context
  computeSquare           // worker function
);

disp(results);


Notes / Tips

  • parallel.parfor(start, end, step, workers, ...) is ideal for independent iterations (each index can be processed without depending on others).

  • If each iteration is very small, overhead can dominate—parallelization shines when each iteration does enough work (heavy math, IO, processing large chunks).

  • A common pattern is a parameter sweep: run the same simulation with many input values and collect outputs.