2

I would like to speed up "times" operation(^) in R.

x <- rnorm(2e+5)
require(rbenchmark)
benchmark(x^(3.33), x^2, x^1, replications = 500)
      test replications elapsed relative user.self sys.self user.child sys.child
1 x^(3.33)          500    9.22    46.10      9.03     0.04         NA        NA
3      x^1          500    5.47    27.35      5.36     0.10         NA        NA
2      x^2          500    0.20     1.00      0.17     0.04         NA        NA

Can I somehow speed up the first operation (x^(3.33))?

Why x^1 is so slow?

P.S. Where can I find the code of ^ operator?

https://github.com/wch/r-source/blob/f68b30e3b5479d84adbff516d48d4722a574dc82/src/main/arithmetic.c#L200

minem
  • 3,640
  • 2
  • 15
  • 29
  • 3
    Improving on .01 seconds to exponentiate 200,000 values suggests you have very high standards. I'm not sure what the exact algorithm R uses is, but it's probably very similar to one of the C algorithms in a different question (https://stackoverflow.com/a/213043/1017276). Notice the discussion about how the special case of a power of 2 may be shifted for efficiency. – Benjamin Jun 06 '17 at 13:47
  • 3
    The source is basically here: https://github.com/wch/r-source/blob/f68b30e3b5479d84adbff516d48d4722a574dc82/src/main/arithmetic.c#L200 – MrFlick Jun 06 '17 at 13:58
  • When I run your benchmarks (R 3.4.0, 64-bit MacOS) I get nearly identical results between `x^1` and `x^(3.3)`, so maybe there's a fluke there. `x^1` isn't recognized as a special. If you really need to speed things up you could probably write Rcpp code to do the multiplication without any checking for infinite/NaN values – Ben Bolker Jun 06 '17 at 14:15

0 Answers0