这是使用我的一个包并并行化的解决方案。请注意,github 上的当前构建不稳定,因此您必须从昨天的先前提交中安装。
编辑:v0.7.1 现在稳定了,你不需要使用 commit-ref
只有当两个矩阵都非常大和/或您有很多内核时,此解决方案才会更快。但我写起来很有趣,所以:
devtools::install_github("alexwhitworth/imputation",
ref= "75723b769ed2ceae8c915d00089a31f059e447aa")
library(microbenchmark)
library(parallel)
f <- function(a, b) {
nnodes <- detectCores()
cl <- makeCluster(nnodes)
d <- do.call("cbind", clusterApply(cl, x= parallel:::splitRows(a, nnodes),
fun= function(x_sub, b) {
apply(x_sub, 1, function(i, b) {imputation::dist_q.matrix(x= rbind(i, b), ref= 1L, q=2)}, b= b)
}, b= b))
stopCluster(cl)
return(d)
}
a <- matrix(rnorm(50000), 1000)
b <- matrix(rnorm(50000), 1000)
d <- matrix(NA, 1000, 1000)
# run on 4 cores
microbenchmark(jogo= for (i in 1:nrow(a)) for (j in 1:nrow(b)) d[i,j] <- sqrt(sum((a[i,]-a[j,])^2)),
alex= f(a,b), times= 10L)
Unit: seconds
expr min lq mean median uq max neval cld
jogo 4.190531 4.196546 4.289265 4.265351 4.358022 4.486445 10 b
alex 3.585672 3.603485 3.783583 3.760859 3.966435 4.048676 10 a
如果你真的想的话,你可能可以使用library(Rdsm) 来改进这一点……但我建议你使用 jogo 的答案。