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

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

问题描述

我有一台运行Windows XP的四核笔记本电脑,但看着Task Manager 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循环.我总是使用"try"包装器来确保操作失败的所有迭代都被丢弃,并且不会破坏本来很好的数据.您将需要指定".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天全站免登陆