如何让 R 使用所有处理器? [英] How to make R use all processors?

查看:39
本文介绍了如何让 R 使用所有处理器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台运行 Windows XP 的四核笔记本电脑,但查看任务管理器 R 似乎一次只使用一个处理器.如何让 R 使用所有四个处理器并加速我的 R 程序?

I have a quad-core laptop running Windows XP, but looking at Task Manager R only ever seems to use one processor at a time. How can I make R use all four processors and speed up my R programs?

推荐答案

我有一个基本系统,用于在for"循环上并行化我的程序.一旦您了解需要做什么,此方法就很简单.它仅适用于本地计算,但这似乎是您所追求的.

I have a basic system I use where I parallelize my programs on the "for" loops. This method is simple once you understand what needs to be done. It only works for local computing, but that seems to be what you're after.

您需要安装这些库:

library("parallel")
library("foreach")
library("doParallel")

首先你需要创建你的计算集群.我通常在运行并行程序时做其他事情,所以我喜欢保持一个开放.detectCores"函数将返回您计算机中的内核数.

First you need to create your computing cluster. I usually do other stuff while running parallel programs, so I like to leave one open. The "detectCores" function will return the number of cores in your computer.

cl <- makeCluster(detectCores() - 1)
registerDoParallel(cl, cores = detectCores() - 1)

接下来,使用foreach"命令以及 %dopar% 运算符调用您的 for 循环.我总是使用尝试"包装器来确保操作失败的任何迭代都被丢弃,并且不会破坏其他良好的数据.您需要指定.combine"参数,并将任何必要的包传递到循环中.请注意,i"是用等号定义的,而不是in"运算符!

Next, call your for loop with the "foreach" command, along with the %dopar% operator. I always use a "try" wrapper to make sure that any iterations where the operations fail are discarded, and don't disrupt the otherwise good data. You will need to specify the ".combine" parameter, and pass any necessary packages into the loop. Note that "i" is defined with an equals sign, not an "in" operator!

data = foreach(i = 1:length(filenames), .packages = c("ncdf","chron","stats"),
               .combine = rbind) %dopar% {
  try({
       # your operations; line 1...
       # your operations; line 2...
       # your output
     })
}

完成后,清理:

stopCluster(cl)

这篇关于如何让 R 使用所有处理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆