I am trying to generate intertime values - given the vector say, 20, 30, 69, 89, 200, what is the difference between each pair?
The data set contains 25 m elements, so I looked at both R and RCpp for the solution - speed is important. The implementation of R was:
intertime <- function(x){
output <- x[2:length(x)] - x[1:(length(x)-1)]
return(output)
}
C ++ implementation:
NumericVector intertime(NumericVector timestamps) {
int input_size = timestamps.size();
NumericVector output(input_size-1);
for(int i = 1; i < input_size;++i){
output[i-1] = (timestamps[i] - timestamps[i-1]);
}
return output;
}
The implementation of C ++ is an order of magnitude faster than the implementation of R. I understand that R is optimized for vectorized operations, so the difference in speed is so small that it doesn’t shock me very much, but: can anyone think of a decent way to perform such operations in Rcpp / C ++, which is more efficient?
source
share