gpt4 book ai didi

c++ - Rcpp 可以替换 R 中的 unif 函数吗?

转载 作者:可可西里 更新时间:2023-11-01 18:15:53 26 4
gpt4 key购买 nike

我刚刚开始使用 R 中的 Rcpp 包,我的学习受到了 Hadley Wickham 的 Advanced R 类(class)的启发。

在 R studio 中,我有以下 .cpp 文件。这个问题更笼统,但这个例子有帮助。

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector runifC(int n, double min=0, double max=1) {
NumericVector out(n);

for(int i = 0; i < n; ++i) {
out[i] = min + ((double) rand() / (RAND_MAX)) * (max - min);
}
return out;
}

/*** R
library(microbenchmark)
microbenchmark(
'R unif-1' = runif(1),
'C++ unif-1' = runifC(1),
'R unif-100' = runif(100),
'C++ unif-100' = runifC(100),
'R unif-1000' = runif(1000),
'C++ unif-1000' = runifC(1000),
'R unif-100000' = runif(100000),
'C++ unif-100000' = runifC(100000)
)
*/

当我获取/保存文件时,它会显示性能输出。

Unit: nanoseconds
expr min lq mean median uq max neval
R unif-1 2061 2644.5 4000.71 3456.0 4297.0 15402 100
C++ unif-1 710 1190.0 1815.11 1685.0 2168.5 5776 100
R unif-100 4717 5566.5 6794.14 6563.0 7435.5 16600 100
C++ unif-100 1450 1997.5 2663.29 2591.5 3107.0 5307 100
R unif-1000 28210 29584.5 31310.54 30380.0 31599.0 52879 100
C++ unif-1000 8292 8951.0 10113.78 9462.5 10121.5 25099 100
R unif-100000 2642581 2975117.0 3104580.62 3030938.5 3119489.0 5435046 100
C++ unif-100000 699833 990924.0 1058855.49 1034430.5 1075078.0 1530351 100

我希望 runif 是一个非常优化的函数,但 C++ 代码运行效率更高。我在这里可能很天真,但如果性能有如此大的差异,那么为什么不是所有适用的 R 函数都用 C++ 重写呢?

这似乎很明显,有很多可能的改进,我觉得我好像错过了为什么不是所有的 R 函数都可以盲目地复制到 C++ 以提高性能的一个重要原因。

编辑:对于此示例,已表明 rand() 的 C++ 实现存在轻微缺陷。我注意到最多的性能差距是使用 rand() 函数。其他功能的性能似乎并不那么激烈,所以我更改了问题的名称。

最佳答案

请不要使用rand()。如果您提交它,这样做也会将您的包裹从 CRAN 中踢出。

参见例如 this C++ reference page警告:

Notes

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls).

如果您对备用随机数生成器和计时感兴趣,Rcpp Gallery .

一般来说,使用 R 提供的生成器,它们具有出色的统计质量,并且由 Rcpp 提供标量和矢量化形式(“Rcpp Sugar”)。

关于c++ - Rcpp 可以替换 R 中的 unif 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26466437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com