I don’t see an easy way in the R database to use vectorized operators to speed this up, but you can use Rcpp to speed up the operation:
library(Rcpp)
get.timeout <- cppFunction("
NumericVector getTimeout(NumericVector timein, NumericVector servtime) {
const int n = timein.size();
NumericVector timeout(n);
timeout[0] = timein[0];
for (int i=1; i < n; ++i) {
timeout[i] = fmax(timein[i], timeout[i-1]) + servtime[i];
}
return timeout;
}")
This is faster than a solution with a for loop:
for.loop <- function(timein, servtime) {
timeout <- dt$timein
n <- length(timeout)
for(i in 2:n) {
timeout[i] <- max(timein[i], timeout[i-1]) + servtime[i]
}
return(timeout)
}
all.equal(for.loop(dt$timein, dt$servtime), get.timeout(dt$timein, dt$servtime))
library(microbenchmark)
microbenchmark(for.loop(dt$timein, dt$servtime), get.timeout(dt$timein, dt$servtime))
The advantage is likely to increase for large entrances.
source
share