c++ - 有效地将数值 vector 的每个元素与前一个元素进行比较

标签 c++ r rcpp

我正在尝试生成间隔值 - 给定一个 vector ,比如 20、30、69、89、200,每一对之间有什么区别?

数据集有 25m 个元素,所以我查看了 R 和 RCpp 的解决方案——速度很重要。 R 实现是:

intertime <- function(x){

    output <- x[2:length(x)] - x[1:(length(x)-1)]
    return(output)
}

C++ 实现:

NumericVector intertime(NumericVector timestamps) {

  //Identify size of input object
  int input_size = timestamps.size();

  //Instantiate output object
  NumericVector output(input_size-1);

  //Loop over the data
  for(int i = 1; i < input_size;++i){

    //For each entry, the output value is [entry] minus [previous entry]
    output[i-1] = (timestamps[i] - timestamps[i-1]);

  }

  //Return
  return output;
}

C++ 实现比 R 实现快约 1 个数量级。我很欣赏 R 在某种程度上针对矢量化操作进行了优化,因此如此小的速度差异不应该让我感到震惊,但是:任何人都可以想出一种在内部执行此类操作的体面方式Rcpp/C++哪个更高效?

最佳答案

在标准 C++ 中有 std::adjacent_difference做你想做的事:

#include <iostream>
#include <numeric>

int main () {
  int val[] = {1,2,3,5,9,11,12};
  int result[7];

  std::adjacent_difference (val, val+7, result);
  for(auto i : result) std::cout << i << " ";
  std::cout << std::endl;
}

LIVE DEMO

关于c++ - 有效地将数值 vector 的每个元素与前一个元素进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264499/

相关文章:

r - 如何评估 data.frame 中的调用?

r - 显示并删除 top_n 最长的 n 个持续时间

r - 为什么 Rtools 3.1 在 Windows 上不支持 C++11

Rcpp 使用外层和 pmax

c++ - rcpp 编译错误

c++ - LLVM 在运行时获取声明函数的参数值

c++ - 如何将 ANSI 字符 (char) 转换为 Unicode 字符 (wchar_t),反之亦然?

r - 使用 dplyr 在 R 中进行动态 CAGR 计算

c++ - 如何调整操作系统级别的文件描述符以最大程度地提升 ASIO 性能

面向 C# 程序员的 C++