3

I tried to test parallel in R with parallel package. But in my example (as the code below), the time for parallel task is greater than that for single task. Anybody can give me some advice?

Thanks so much!

##parSquareNum.R
strt <- Sys.time()
workerFunc <- function(n) { return(n^2) }
values <- 1:1000000
library(parallel)
## Number of workers (R processes) to use:
cores <- detectCores()
## Set up the ’cluster’
cl <- makeCluster(cores-1)
## Parallel calculation (parLapply):
res <- parLapply(cl, values, workerFunc)
## Shut down cluster
write(Sys.time()-strt, 'parallel.txt')
stopCluster(cl)

##singleSquareNum.R

## The worker function to do the calculation:
strt <- Sys.time()
workerFunc <- function(n) { return(n^2) }
## The values to apply the calculation to:
values <- 1:1000000
## Serial calculation:
res <- lapply(values, workerFunc)
##print(unlist(res))
write(Sys.time() -strt, 'single.txt')
1
  • 1
    Parallelism is unlikely to be of benefit for simple tasks at the core because the dispatch and reassembly process takes time as well. Parceling out complex tasks will be needed to demonstrate benefit. Commented Jun 1, 2015 at 17:26

1 Answer 1

4

The main reason you are seeing this is because loading the library plus making the cluster takes some time. Move the strt <- Sys.time() to right before res and you will see a difference, especially if you increase the value of values

##parSquareNum.R
workerFunc <- function(n) { return(n^2) }
values <- 1:1000000
library(parallel)
## Number of workers (R processes) to use:
cores <- detectCores()
## Set up the ’cluster’
cl <- makeCluster(cores-1)
## Parallel calculation (parLapply):
strt <- Sys.time()
res <- parLapply(cl, values, workerFunc)
write(Sys.time()-strt, 'parallel.txt')
## Shut down cluster
stopCluster(cl)

##singleSquareNum.R

## The worker function to do the calculation:
workerFunc <- function(n) { return(n^2) }
## The values to apply the calculation to:
values <- 1:1000000
## Serial calculation:
strt <- Sys.time()
res <- lapply(values, workerFunc)
##print(unlist(res))
write(Sys.time() -strt, 'single.txt')

When I run I get 0.6941409 sec for parallel and 1.117002 sec for single. 1.6X speedup. I am running on an i7 chip.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.