衡量收益

R 并行编程

Nabeel Imam

Data Scientist

玩具示例

numbers <- 1:1000000


# 顺序执行 sqroots <- lapply(numbers, sqrt)
# 并行执行 cl <- makeCluster(4) sqroots <- parLapply(cl, numbers, sqrt) stopCluster(my_cluster)

哪种更快?

R 并行编程

性能基准测试

多次运行代码以估计平均执行时间

library(microbenchmark)


microbenchmark( "Sequential" = lapply(numbers, sqrt),
"Parallel" = { cl <- makeCluster(4) parLapply(cl, numbers, sqrt) stopCluster(my_cluster) },
times = 10 )

 

 

Unit: milliseconds
      expr     min    mean     max neval
Sequential  633.96  838.09  993.59    10
  Parallel 1136.95 1247.29 1557.58    10
  • 简单数值运算很少因并行而受益
  • Profiling 提供逐行报告,Benchmarking 给出整体耗时
R 并行编程

显而易见的问题

sqroots <- sqrt(numbers)

一头大象坐在客厅沙发上,人们注意到了它的存在。

R 并行编程

向量化

sqroots <- sqrt(numbers)
  • 基础 R 函数如 sqrt() 是向量化的。
  • 将单个函数映射到多个输入
  • 很快,但仅适用于简单操作
microbenchmark(
  "Vectorized" = sqrt(numbers),
  "Sequential" = lapply(numbers, sqrt),
  "Parallel" = {
    cl <- makeCluster(4)
    parLapply(cl, numbers, sqrt)
    stopCluster(my_cluster)
  },
  times = 10)
Unit: milliseconds
      expr       min      mean      max neval
Vectorized    2.3904    9.2071   66.303    10
Sequential  352.1166  771.7491 1004.753    10
  Parallel 1191.3176 1377.6926 1700.316    10
R 并行编程

自助法(Bootstrap)

从当前数据中有放回抽样

print(ls_df)
$`2001`
   Country             Life_expectancy  Year
 1 Afghanistan                    56.3  2001
 2 Albania                        74.3  2001
 3 Algeria                        71.1  2001
...
$`2002`
   Country             Life_expectancy  Year
 1 Afghanistan                    56.8  2002
 2 Albania                        74.6  2002
 3 Algeria                        71.6  2002
...
R 并行编程

经典做法

df <- ls_df$`2001`


estimates <- rep(0, 10000)
for (i in 1:10000) { b <- sample(df$Life_expectancy, replace = T)
estimates[i] <- mean(b) }

2001 年全球平均预期寿命的自助抽样估计直方图,呈经典钟形曲线。

  • 用分位数求置信区间:quantile(estimates, c(0.025, 0.975))
R 并行编程

好消息

自助法可并行化

estimates <- rep(0, 10000)

for (i in 1:10000) {

  b <- sample(df$Life_expectancy,
              replace = T)

  estimates[i] <- mean(b)
  }
boot_dist <- function (df) {

  estimates <- rep(0, 10000)

  for (i in 1:10000) {
    b <- sample(df$Life_expectancy, replace = T)
    estimates[i] <- mean(b)
  }

  return(estimates)
}


cl <- makeCluster(4) ls_dists <- parLapply(cl, ls_df, boot_dist) stopCluster(cl)
R 并行编程

收益

microbenchmark(
  "lapply" = lapply(ls_df, boot_dist),
  "parLapply" = {
    cl <- makeCluster(4)
    parLapply(cl, ls_df, boot_dist)
    stopCluster(cl)
  },
  times = 10
)
Unit: seconds
     expr    min   mean    max neval
   lapply 3.6938 4.2184 4.5267    10
parLapply 1.9006 2.5166 2.7292    10

如何实现:

  • 分析现有代码,找出最慢环节
  • 将此步并行化/优化
  • 基准测试并比较
R 并行编程

Vamos praticar!

R 并行编程

Preparing Video For Download...