Search code examples
elisp

Is there a simple way to time a function call in elisp?


Yes, I am aware of the emacs profiler feature. I'm looking for something similar to the time keyword in bash, something like:

(time (myfunc)) 

which would return or print the time taken by the myfunc call. Is there such a thing?


Solution

  • benchmark.el provides benchmark-run and benchmark-run-compiled functions as well as a benchmark version to run interactively. The linked example:

    C-u 512 M-x benchmark (sort (number-sequence 1 512) '<)
    Elapsed time: 0.260000s (0.046000s in 6 GCs)

    The timer used by all those functions is the benchmark-elapse macro, which you can also use directly if desired:

    ELISP> (require 'benchmark)
    ELISP> (benchmark-elapse
             (sit-for 2))
    2.00707889