Robinlovelace / overline-tests

Testing overline functionality
0 stars 0 forks source link

Rcpp test #1

Open mem48 opened 1 year ago

mem48 commented 1 year ago

Thinking about this, going Rcpp is probably the best way to speed up.

My C++ is not great but ChatGPT seems to be good at translating code from R to C++

E.g. the code for Transposing B to A into A to B

rfunc= function(c3){
  t(apply(c3, MARGIN = 1, FUN = function(y) {
    if (y[1] != y[3]) {
      if (y[1] > y[3]) {
        c(y[3], y[4], y[1], y[2])
      } else {
        y
      }
    } else {
      if (y[2] > y[4]) {
        c(y[3], y[4], y[1], y[2])
      } else {
        y
      }
    }
  }))
}

library(Rcpp)
cppFunction('NumericMatrix rcpp_function(NumericMatrix c3) {
  int nrow = c3.nrow();
  NumericMatrix out(nrow, 4);

  for (int i = 0; i < nrow; ++i) {
    NumericVector y = c3(i, _);
    if (y[0] != y[2]) {
      if (y[0] > y[2]) {
        out(i, _) = NumericVector::create(y[2], y[3], y[0], y[1]);
      } else {
        out(i, _) = y;
      }
    } else {
      if (y[1] > y[3]) {
        out(i, _) = NumericVector::create(y[2], y[3], y[0], y[1]);
      } else {
        out(i, _) = y;
      }
    }
  }

  return out;
}')

bench::mark(r1 = rcpp_function(x),
            r2 = rfunc(x))

# A tibble: 2 × 13
  expression      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result   memory    
  <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list>   <list>    
1 r1         623.02ms 623.02ms     1.61     89.3MB     1.61     1     1   623.02ms <dbl[…]> <Rprofmem>
2 r2            7.52s    7.52s     0.133   401.9MB     1.73     1    13      7.52s <dbl[…]> <Rprofmem>
# ℹ 2 more variables: time <list>, gc <list>
Robinlovelace commented 1 year ago

Impressive speed-up!