小编ech*_*ski的帖子

Rcpp中单个"for"循环的意外性能

有人可以向我解释使用Rcpp编写的简单for循环的奇怪行为(代码如下).基于微基准测试输出,似乎算法的复杂性for_iteration是恒定的,基于其代码是不正确的.为了比较,我测试了函数for_double_iteration,其行为与代码复杂性一致.此代码在Ubuntu 16.04和CPU Intel Core i3-6100上运行,但在Windows 7和CPU Intel Core i5-2300上获得了相同的结果.

这是代码:

library(Rcpp)
library(microbenchmark)
 sourceCpp(code='
  #include <Rcpp.h>

  // [[Rcpp::export]]
  int for_iteration(const int n) {
    int j = 0;
    for (int i = 0; i < n; i++) {
      j++;
    }
    return (j);
  }

  // [[Rcpp::export]]
  int for_double_iteration(const int n) {
    int j = 0, k = 0;
    for (int i = 0; i < n; i++) {
      for (k = 0; k < i; k++) {
        j++;
      } …
Run Code Online (Sandbox Code Playgroud)

c performance for-loop r rcpp

1
推荐指数
1
解决办法
84
查看次数

标签 统计

c ×1

for-loop ×1

performance ×1

r ×1

rcpp ×1