R's JIT compiler

2017-09-11

A couple of days ago I was giving a course on R, and I used the following example\footnote{This function calculates the value of an American call option using a binomial tree.}:

library(fOptions)
system.time(CRRBinomialTreeOption(TypeFlag = "ca", S = 50, X = 50, Time = 5/12, r = 0.1, b = 0.1, sigma = 0.4, n = 2000)@price)
##    user  system elapsed 
##   7.807   0.034   8.002

I was puzzled that on my laptop it took about 8 seconds to compute and on the lab computers it took less the 2 seconds. Since my laptop has a relatively recent CPU, and similar to the ones on the lab computers, I could not explain the difference in performance

Only later it occurred to me that I’m still using R 3.3.3 and the lab computers had 3.4 installed.

Version 3.4 enabled the Just In Time (JIT) byte-code compiler by default at its level 3. This setting can result in a significantly higher execution speed, as functions will be compiled before execution on the first or second use. The impact is larger on code that uses loops, which is the case of this function.

The JIT is not a new R feature, it was already available in previous versions, but it was not enabled by default. To test if this explained the difference in performance, I compiled the function and called the compiled version on the laptop:

library(compiler)
compCRRBin <- cmpfun(CRRBinomialTreeOption)

system.time(compCRRBin(TypeFlag = "ca", S = 50, X = 50, Time = 5/12, r = 0.1, b = 0.1, sigma = 0.4, n = 2000)@price)
##    user  system elapsed 
##   2.260   0.010   2.289

And low and behold I now get a similar result. It is possible to enable the same behaviour on previous R versions by calling:

enableJIT(3)

this will set the JIT compiler by default at its level 3. Or, one could simply upgrade to the newer R version.