监控与管理内存

R 并行编程

Nabeel Imam

Data Scientist

队列与空间

银行有三位柜员为顾客服务,其他顾客在排队等候。

R 并行编程

并行流程

并行流程示意:任务被拆分为多个子任务,由不同核心执行,再合并结果。

R 并行编程

并行流程

并行流程在随机存取内存(RAM)中运行。

R 并行编程

出生数据

print(ls_files)
 [1] "./births/AK.csv"
 [2] "./births/AL.csv"
 [3] "./births/AR.csv"
 [4] "./births/AZ.csv"
 [5] "./births/CA.csv"
 [6] "./births/CO.csv"
 [7] "./births/CT.csv"
 [8] "./births/DC.csv"
 [9] "./births/DE.csv"
 [10] "./births/FL.csv"
...
R 并行编程

使用 futures 进行映射

plan(multisession, workers = 2)

ls_df <- future_map(ls_files, read.csv)
plan(sequential)
print(ls_df)
[[1]]
   state month plurality weight_gain_pounds mother_age
      AK     1         1                 30         43
   ...
[[2]]
   state month plurality weight_gain_pounds mother_age
      AL    10         1                 60         33
   ...
...
R 并行编程

两名 worker 的分析

profvis({
  plan(multisession, workers = 2)
  ls_df <- future_map(ls_files, read.csv)
  plan(sequential)
})

由 profvis 生成的性能分析输出。使用 future_map 以两名 worker 并行读取 CSV 占用 1.6 MB 内存,其他代码行未记录内存使用。

R 并行编程

四名 worker 的分析

profvis({
  plan(multisession, workers = 4)
  ls_df <- future_map(ls_files, read.csv)
  plan(sequential)
})

由 profvis 生成的性能分析输出。使用 future_map 以四名 worker 并行读取 CSV 占用 3.1 MB 内存,设置 multisession 占用 0.3 MB。

R 并行编程

幕后原理

美国地图,按西部、中西部、南部、东北四个区域划分。每个区域对应一个包含该区域各州数据的 CSV 文件列表。

R 并行编程

用分块管理内存

config <- furrr_options(chunk_size = 26)

plan(multisession, workers = 4) ls_df <- future_map(ls_files, read.csv,
.options = config) plan(sequential)
R 并行编程

用分块管理内存

profvis({
  config <- furrr_options(chunk_size = 26)
  plan(multisession, workers = 4)
  ls_df <- future_map(ls_files, read.csv,
             .options = config)
  plan(sequential)
})

由 profvis 生成的性能分析输出。使用 future_map 以四名 worker 并行读取 CSV,分块大小为 26,内存占用为 2.5 MB。

R 并行编程

parallel 的分块

cl <- makeCluster(4)


ls_df <- parLapply(cl, ls_files, read.csv)
stopCluster(cl)

使用 parLapply 并行读取 CSV 占用 2.4 MB 内存,全部由 parLapply 调用产生。

R 并行编程

parallel 的分块

cl <- makeCluster(4)
ls_df <- parLapply(cl, ls_files, read.csv,

chunk.size = 26)
stopCluster(cl)

当 chunk.size 设为 26 时,使用 parLapply 并行读取 CSV 仅占用 1 MB 内存。

R 并行编程

何时分块?

  • 分块默认已较优
  • 处理大对象且内存紧张时
    • 如可行,尝试减少核心数
    • 试验不同分块大小以达最佳
R 并行编程

Passons à la pratique !

R 并行编程

Preparing Video For Download...