Timing Execution In Emacs

Xah Lee has a short post on find-file vs. with-temp-buffer for loading a large number of files. The results were sort of surprising, at least to me, so you should take a look if you need to load several files in Emacs. His post was basically a little benchmark and I vaguely wondered how he did the timing. Scheme and Common Lisp have functions for this but I had never seen anything for Elisp.

Just now, while looking at something completely unrelated I came across the benchmark-run command. It does just exactly what its name suggests: if you want to time some Elisp code you just wrap it with benchmark-run and go. It will report the elapsed time for execution, the number of garbage collections that ran, and the time spent in the garbage collector.

For example, suppose we want to run some-function on several files that are marked in a Dired buffer. We could do something like

(benchmark-run 1 (mapc 'some-function (dired-get-marked-files)))

to time how long it takes. The first argument (1) says to run the benchmark 1 time. You can set that to a larger number if you want to time several runs to get a better idea of average performance.

That's a pretty nifty thing to know and I don't recall ever seeing it anywhere before. That's one of the nice things about Emacs: there's always something new to learn.

Update: Lisp → Common Lisp

This entry was posted in Programming and tagged , . Bookmark the permalink.

One Response to Timing Execution In Emacs

  1. Xah Lee says:

    hi jcs,

    i should issue a correction. In by previous report, the speed difference is by a factor of 45.
    But actually it should be just 5.

    My mistake was because i had personal init file that caused the slow down. I have hooks for both find-file and html-mode.

    I've updated the article. Big thanks to another emacs lisp hacker Trey Jackson.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>