[英]Why Rcpp::warning() is slower than R warning?
考虑以下函数foo
和bar
(仅在打印警告时有所不同)及其R等效项fooR
和barR
:
cppFunction('
void foo () {
int i = 0;
while (i < 1e3) {
i++;
}
return;
}')
cppFunction('
void bar () {
int i = 0;
while (i < 1e3) {
i++;
Rcpp::warning("hello world!");
}
return;
}')
fooR <- function() {
i = 0;
while (i < 1e3) {
i = i+1;
}
}
barR <- function() {
i = 0;
while (i < 1e3) {
i = i+1;
warning("hello world!")
}
}
显然,打印警告会使功能变慢,但是R和Rcpp之间的差异是巨大的(慢200倍,慢5000倍!):
> benchmark(foo(), bar())
test replications elapsed relative user.self sys.self user.child sys.child
2 bar() 100 5.156 5156 5.156 0 0 0
1 foo() 100 0.001 1 0.000 0 0 0
There were 50 or more warnings (use warnings() to see the first 50)
> benchmark(fooR(), barR())
test replications elapsed relative user.self sys.self user.child sys.child
2 barR() 100 11.102 213.5 11.104 0 0 0
1 fooR() 100 0.052 1.0 0.052 0 0 0
There were 50 or more warnings (use warnings() to see the first 50)
为什么会这样呢? 可以预防吗?
我不确定您是否从基准中意识到Rcpp
是:
现在,当你扔一个警告,在这两个 Rcpp
和base R
,以下是发生:
STDERR
流。 (因此,红色文本而不是STDOUT
的黑色) STDERR
在Rcpp
,低级引用有助于减少重复上述过程并将控制权返回给循环(与位于堆栈中较高位置的R的处理程序相比)所需的总时间。
同样,用Rcpp完成此操作所花费的时间是正常的,因为必须将对过程的控制权让回R,打印消息,然后返回循环。 考虑纯循环情况下速度损失的最佳方法是您决定在C ++循环中调用基于R的函数,而不是期望加速的R循环。
老实说,我对Rcpp
能够比R等效快2 Rcpp
到惊讶。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.