繁体   English   中英

为什么Rcpp :: warning()比R警告慢?

[英]Why Rcpp::warning() is slower than R warning?

考虑以下函数foobar (仅在打印警告时有所不同)及其R等效项fooRbarR

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是:

  1. 发出警告的速度提高了11.102 / 5.156 = 2.15322倍
  2. 在纯循环情况下,0.052 / 0.001 = 快52倍

现在,当你扔一个警告,在这两个 Rcppbase R ,以下是发生:

  1. 打开到STDERR流。 (因此,红色文本而不是STDOUT的黑色)
  2. 写信息
  3. 关闭STDERR
  4. 继续说明。

Rcpp ,低级引用有助于减少重复上述过程并将控制权返回给循环(与位于堆栈中较高位置的R的处理程序相比)所需的总时间。

同样,用Rcpp完成此操作所花费的时间是正常的,因为必须将对过程的控制权让回R,打印消息,然后返回循环。 考虑纯循环情况下速度损失的最佳方法是您决定在C ++循环中调用基于R的函数,而不是期望加速的R循环。

老实说,我对Rcpp能够比R等效快2 Rcpp到惊讶。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM