title: How can I make a parallel operation faster than the serial version?
body: <p>I'm attempting to "map" a function onto an array. However when trying both simple and complex functions, the parallel version is always slower than the serial version. How can I improve the performance of a parallel computation in R?</p>
  
  <p><strong>Simple parallel example:</strong></p>
  
  <pre><code>library(parallel)
  
  # Number of elements
  arrayLength = 100
  # Create data
  input = 1:arrayLength
  
  # A simple computation
  foo = function(x, y) x^y - x^(y-1)
  
  # Add complexity
  iterations = 5 * 1000 * 1000
  
  # Perform complex computation on each element
  compute = function (x) {
    y = x
    for (i in 1:iterations) {
      x = foo(x, y)
    }
    return(x)
  }
  
  # Parallelized compute
  computeParallel = function(x) {
    # Create a cluster with 1 fewer cores than are available.
    cl &lt;- makeCluster(detectCores() - 1) # 8-1 cores 
    # Send static vars &amp; funcs to all cores
    clusterExport(cl, c('foo', 'iterations'))
    # Map
    out = parSapply(cl, x, compute)
    # Clean up
    stopCluster(cl)
    return(out)
  }
  
  system.time(out &lt;- compute(input)) # 12 seconds using 25% of cpu
  system.time(out &lt;- computeParallel(input)) # 160 seconds using 100% of cpu
  </code></pre>