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.