Created
December 2, 2017 21:58
-
-
Save javieroot/aa7145d84e3fafb419e6e6c95f0c68a9 to your computer and use it in GitHub Desktop.
Some sample Rcpp code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(Rcpp) | |
# Simple addition | |
add_r <- function(x, y, z) { | |
sum = x + y + z | |
return(sum) | |
} | |
cppFunction( | |
"int add_c(int x, int y, int z) { | |
int sum = x + y + z; | |
return sum; | |
}") | |
add_r(1, 2, 3) | |
add_c(1, 2, 3) | |
# Euclidean distance | |
dist_r <- function(x, ys) { | |
sqrt((x - ys) ^ 2) | |
} | |
cppFunction( | |
"NumericVector dist_c(double x, NumericVector ys) { | |
int n = ys.size(); | |
NumericVector out(n); | |
for(int i = 0; i < n; i++) { | |
out[i] = sqrt(pow(ys[i] - x, 2.0)); | |
} | |
return out; | |
}") | |
dist_r(10, 20:25) | |
dist_c(10, 20:25) | |
# Summation with conditionals | |
sum_r <- function(v) { | |
total <- 0 | |
for (e in v) { | |
if (e < 0) { total = total - e } | |
else if (e > 0.75) { total = total + e/2 } | |
else { total = total + e } | |
} | |
return(total) | |
} | |
cppFunction( | |
"double sum_c(NumericVector v) { | |
double total = 0; | |
for (int i = 0; i < v.size(); i++) { | |
if (v[i] < 0) { total -= v[i]; } | |
else if (v[i] > 0.75) { total += v[i]/2; } | |
else { total += v[i]; } | |
} | |
return(total); | |
}") | |
v <- runif(100000, -1, 1) | |
microbenchmark::microbenchmark(sum_r(v), sum_c(v)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment