简体   繁体   English

在R问题中并行运行

[英]Running parallel in R problems

I tried to test parallel in R with parallel package. 我尝试使用并行包在R中测试并行。 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')

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 strt <- Sys.time()移至res之前,您会看到差异,特别是如果您增加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. 当我运行时,并行获得0.6941409秒,单个获得1.117002秒。 1.6X speedup. 1.6倍加速。 I am running on an i7 chip. 我在i7芯片上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM