Please look at the following small working example:
#### Pseudo data
nobs1 <- 4000
nobs2 <- 5000
mylon1 <- runif(nobs1, min=0, max=1)-76
mylat1 <
I ran this 3 times, once as you have here, once loading up library compiler (in base R) and running enableJIT(3), and running (with enableJIT) after compiling your thedistance function with cmpfun() (in compiler). The results are (respectively):
> proc.time() - ptm
user system elapsed
335.26 0.17 339.83
> proc.time() - ptm
user system elapsed
120.73 0.12 122.52
> proc.time() - ptm
user system elapsed
117.86 0.12 118.95
The difference with 2 and 3 is neglible, as I think enableJIT just compiles the function anyway, but it looks like there is a decent improvement with enableJIT alone. so just throw
library(compiler)
enableJIT(3)
at the top of your code.
More information can be found here