【发布时间】:2013-01-30 21:38:57
【问题描述】:
我正在尝试确定何时使用parallel 包来加快运行某些分析所需的时间。我需要做的一件事是创建矩阵来比较具有不同行数的两个数据帧中的变量。我在StackOverflow 上问了一个关于有效执行方式的问题,并在我的blog 上写了关于测试的文章。因为我对最好的方法感到满意,所以我想通过并行运行来加速这个过程。以下结果基于具有 8GB RAM 的 2ghz i7 Mac。我很惊讶parallel 包,尤其是parSapply 函数,比仅使用apply 函数更糟糕。复制它的代码如下。请注意,我目前只使用我创建的两列之一,但最终想同时使用。
(来源:bryer.org)
require(parallel)
require(ggplot2)
require(reshape2)
set.seed(2112)
results <- list()
sizes <- seq(1000, 30000, by=5000)
pb <- txtProgressBar(min=0, max=length(sizes), style=3)
for(cnt in 1:length(sizes)) {
i <- sizes[cnt]
df1 <- data.frame(row.names=1:i,
var1=sample(c(TRUE,FALSE), i, replace=TRUE),
var2=sample(1:10, i, replace=TRUE) )
df2 <- data.frame(row.names=(i + 1):(i + i),
var1=sample(c(TRUE,FALSE), i, replace=TRUE),
var2=sample(1:10, i, replace=TRUE))
tm1 <- system.time({
df6 <- sapply(df2$var1, FUN=function(x) { x == df1$var1 })
dimnames(df6) <- list(row.names(df1), row.names(df2))
})
rm(df6)
tm2 <- system.time({
cl <- makeCluster(getOption('cl.cores', detectCores()))
tm3 <- system.time({
df7 <- parSapply(cl, df1$var1, FUN=function(x, df2) { x == df2$var1 }, df2=df2)
dimnames(df7) <- list(row.names(df1), row.names(df2))
})
stopCluster(cl)
})
rm(df7)
results[[cnt]] <- c(apply=tm1, parallel.total=tm2, parallel.exec=tm3)
setTxtProgressBar(pb, cnt)
}
toplot <- as.data.frame(results)[,c('apply.user.self','parallel.total.user.self',
'parallel.exec.user.self')]
toplot$size <- sizes
toplot <- melt(toplot, id='size')
ggplot(toplot, aes(x=size, y=value, colour=variable)) + geom_line() +
xlab('Vector Size') + ylab('Time (seconds)')
【问题讨论】:
-
(+1) 很好的表述,我觉得很有趣! (除了博客插件:))
-
抱歉,我不是说它是一个插件 :-) 只是想提供我目前拥有的所有信息。
标签: r parallel-processing