【发布时间】:2015-06-12 15:20:50
【问题描述】:
我正在尝试对矩阵的每一列进行累积总和。这是我在 R 中的代码:
testMatrix = matrix(1:65536, ncol=256);
microbenchmark(apply(testMatrix, 2, cumsum), times=100L);
Unit: milliseconds
expr min lq mean median uq max neval
apply(testMatrix, 2, cumsum) 1.599051 1.766112 2.329932 2.15326 2.221538 93.84911 10000
我使用了 Rcpp 进行比较:
cppFunction('NumericMatrix apply_cumsum_col(NumericMatrix m) {
for (int j = 0; j < m.ncol(); ++j) {
for (int i = 1; i < m.nrow(); ++i) {
m(i, j) += m(i - 1, j);
}
}
return m;
}');
microbenchmark(apply_cumsum_col(testMatrix), times=10000L);
Unit: microseconds
expr min lq mean median uq max neval
apply_cumsum_col(testMatrix) 205.833 257.719 309.9949 265.986 276.534 96398.93 10000
所以 C++ 代码的速度是原来的 7.5 倍。在纯 R 中是否有可能比 apply(testMatrix, 2, cumsum) 做得更好?感觉就像我无缘无故地有一个数量级的开销。
【问题讨论】:
-
您可以尝试通过
compile:cmpfun和该库中的其他工具进行编译。但是,众所周知R与MATLAB和类似语言一样,由于在命令时“编译”而具有大量开销。这就是为什么人们在需要最大速度时会在 Fortran 或 cpp 中编写函数的核心。 -
apply(testMatrix, 2, cumsum)的快速替代方案是matrixStats::colCumsums(testMatrix)。 -
@Khashaa,我想你的比 R 更快,因为它也使用 C 代码。我相信作者是在询问严格的 R 实现。
-
Khashaa 的方法要求用户仅调用 R 函数,我认为这是 OP 正在寻找的。许多“R”函数实际上是 C 或 C++。在我的电脑上,
matrixStats包中的colCumsums实际上比 Rcpp 函数快大约 35%。 -
@cdeterman 很高兴知道所有选项!