::cppFunction('double weighted_sum(NumericVector x, NumericVector w){
Rcpp int n = x.size();
double sum = 0;
for(int i = 0; i < n; ++i){
sum += x[i]*w[i];
}
return sum;
}')
Class activity solutions
<- rnorm(1000)
x <- runif(1000)
w
::mark(
benchweighted_sum(x, w),
sum(x * w),
crossprod(x, w),
check = F
)
# A tibble: 3 × 6
expression min median `itr/sec` mem_alloc `gc/sec`
<bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
1 weighted_sum(x, w) 2.46µs 3.33µs 297448. 2.49KB 0
2 sum(x * w) 112.67µs 114.71µs 8621. 7.86KB 2.03
3 crossprod(x, w) 2.58µs 2.75µs 355831. 2.23KB 0
::cppFunction('double varC(NumericVector x){
Rcpp int n = x.size();
double mean = 0;
for(int i = 0; i < n; ++i){
mean += x[i]/n;
}
double sum = 0;
for(int i = 0; i < n; ++i){
sum += pow(x[i] - mean, 2);
}
return sum/(n-1);
}')
<- rnorm(1000)
x
::mark(
benchvar(x),
varC(x)
)
# A tibble: 2 × 6
expression min median `itr/sec` mem_alloc `gc/sec`
<bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
1 var(x) 325.25µs 326.5µs 3013. 13.71KB 0
2 varC(x) 3.12µs 3.5µs 266347. 2.49KB 0
::cppFunction('NumericMatrix matrix_prod(NumericMatrix A, NumericMatrix B){
Rcpp int ncol_a = A.ncol();
int nrow_a = A.nrow();
int ncol_b = B.ncol();
int nrow_b = B.nrow();
NumericMatrix result(nrow_a, ncol_b);
for(int i = 0; i < nrow_a; ++i){
for(int j = 0; j < ncol_b; ++j){
double sum = 0;
for(int k = 0; k < ncol_a; ++k){
sum += A(i,k)*B(k,j);
}
result(i,j) = sum;
}
}
return result;
}')
<- matrix(rnorm(10), nrow=2, ncol=5)
A <- matrix(rnorm(15), nrow=5, ncol=3)
B
%*% B A
[,1] [,2] [,3]
[1,] 0.509605 -3.5915745 -5.808356
[2,] -1.572469 0.2583574 -2.714978
matrix_prod(A, B)
[,1] [,2] [,3]
[1,] 0.509605 -3.5915745 -5.808356
[2,] -1.572469 0.2583574 -2.714978