Emacs -- Timing execution of function calls in Emacs lisp
Asked Answered
C

2

13

I'm looking for some assistance, please, to measure the time of a function call when using a while loop -- i.e., the clock should stop when the function throws done. I found the following timer on the mailing list: http://lists.gnu.org/archive/html/help-gnu-emacs/2008-06/msg00087.html

(defmacro measure-time (&rest body)
  "Measure the time it takes to evaluate BODY."
  `(let ((time (current-time)))
     ,@body
     (message "%.06f" (float-time (time-since time)))))

It's used like this:

(measure-time
  (dotimes (i 100000)
    (1+ 1)))

An example of how to use the timer macro with a while loop would be greatly appreciated. I'm looking for the total time beginning from before the while loop commenced to the end when done is thrown.

(defun test ()
  (measure-time)
  (catch 'done
    (while t
      [*** do a bunch of stuff]
      (when (condition-satisfied-p)
        [*** STOP THE CLOCK AND PRINT TOTAL DURATION ***]
        (throw 'done nil) ))))
Corso answered 13/5, 2014 at 3:24 Comment(1)
Notice that if body contains the symbol time you'll have unexpected results. You can avoid such variable capture by using gensym.Cowskin
T
6

Exactly as per the example you've quoted. You literally wrap (measure-time ... ) around the thing you're timing. The entirety of the catch expression, in your case.

Did you not try that?

Transcaucasia answered 13/5, 2014 at 4:48 Comment(1)
Ah, yes, it works now. I didn't realize it was a wrapper -- I had tried placing it at the beginning and at the ending, but not sandwich-ing the catch expression. Thank you very much -- greatly appreciated! :)Corso
H
6

BTW, this macro is called benchmark-elapse in Emacs, but it is not autoloaded, so you need to (require 'benchmark) before using it.

Hackman answered 23/5, 2021 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.