Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically always time functions in R

Tags:

emacs

r

timing

I hacked together an Emacs function in order to send

tOne <- proc.time()[3]

before my "send-to-R" key, followed by

tTwo <- proc.time()[3]

afterwards, then printing the difference. The printing gets quite messy though.

Is there a better way in R to automatically time everything send to R? (such as in F# #time "on")


EDIT: Currently, it sends some extra newlines since the inferior buffer needs the strings to be sent:

> > a<-ocorrelate.parallel(replicate(2, rnorm(100000)), 0.5)


> 
+  user  0.072 sys  0.020 elapsed 14.925 
> > a<-ocorrelate.parallel(replicate(2, rnorm(100000)), 0.5)


> 
+  user  0.088 sys  0.032 elapsed 16.868 
> > 

Function:

(defun ess-timed-cc (vis)
  (interactive "P")
  (process-send-string "R" "tone <- proc.time()[1:3];")
  (ess-eval-region-or-function-or-paragraph-and-step vis)
  (process-send-string "R" "ttwo <- proc.time()[1:3]; cat(paste(c(\"\", 
        format(ttwo-tone)), c(\"user\", \"sys\", \"elapsed\", \"\n\")));")
  (other-window 1)
  (inferior-ess-send-input)
  (inferior-ess-send-input)
  (goto-char (point-max))
  (other-window -1)
  )
like image 968
PascalVKooten Avatar asked Nov 11 '22 23:11

PascalVKooten


1 Answers

You can turn on profiling in R and it will tell you the relative amount of time spent in each function, that may be what you want. See ?Rprof for details.

You could also use addTaskCallback to add a callback to show you the time since the last expression finished, though this time would include any idle time and the time to type the expression, not just the run time. If you have all the commands already in a file and just send them to the command line then this should work reasonably well.

There may also be some hooks that you could set that would start and stop the timing, but not all functions have hooks.

For the emacs solution you could use that to wrap the call in system.time instead of calling proc.time twice and subtracting.

You could also use the trace function to insert the 2 calls to proc.time at the beginning and end of each function that you wanted to time. This would require a vector of the names of the functions that you wanted to time, but ls could help with that.

like image 53
Greg Snow Avatar answered Nov 15 '22 05:11

Greg Snow