Document reserved keys
[emacs.git] / lisp / emacs-lisp / elp.el
blob954e7aa73ae9be20fed89302252ca617e96ffaf9
1 ;;; elp.el --- Emacs Lisp Profiler -*- lexical-binding: t -*-
3 ;; Copyright (C) 1994-1995, 1997-1998, 2001-2018 Free Software
4 ;; Foundation, Inc.
6 ;; Author: Barry A. Warsaw
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Created: 26-Feb-1994
9 ;; Keywords: debugging lisp tools
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; If you want to profile a bunch of functions, set elp-function-list
29 ;; to the list of symbols, then do a M-x elp-instrument-list. This
30 ;; hacks those functions so that profiling information is recorded
31 ;; whenever they are called. To print out the current results, use
32 ;; M-x elp-results. If you want output to go to standard-output
33 ;; instead of a separate buffer, setq elp-use-standard-output to
34 ;; non-nil. With elp-reset-after-results set to non-nil, profiling
35 ;; information will be reset whenever the results are displayed. You
36 ;; can also reset all profiling info at any time with M-x
37 ;; elp-reset-all.
39 ;; You can also instrument all functions in a package, provided that
40 ;; the package follows the GNU coding standard of a common textual
41 ;; prefix. Use M-x elp-instrument-package for this.
43 ;; If you want to sort the results, set elp-sort-by-function to some
44 ;; predicate function. The three most obvious choices are predefined:
45 ;; elp-sort-by-call-count, elp-sort-by-average-time, and
46 ;; elp-sort-by-total-time. Also, you can prune from the output, all
47 ;; functions that have been called fewer than a given number of times
48 ;; by setting elp-report-limit.
50 ;; Elp can instrument byte-compiled functions just as easily as
51 ;; interpreted functions, but it cannot instrument macros. However,
52 ;; when you redefine a function (e.g. with eval-defun), you'll need to
53 ;; re-instrument it with M-x elp-instrument-function. This will also
54 ;; reset profiling information for that function. Elp can handle
55 ;; interactive functions (i.e. commands), but of course any time spent
56 ;; idling for user prompts will show up in the timing results.
58 ;; You can also designate a `master' function. Profiling times will
59 ;; be gathered for instrumented functions only during execution of
60 ;; this master function. Thus, if you have some defuns like:
62 ;; (defun foo () (do-something-time-intensive))
63 ;; (defun bar () (foo))
64 ;; (defun baz () (bar) (foo))
66 ;; and you want to find out the amount of time spent in bar and foo,
67 ;; but only during execution of bar, make bar the master. The call of
68 ;; foo from baz will not add to foo's total timing sums. Use M-x
69 ;; elp-set-master and M-x elp-unset-master to utilize this feature.
70 ;; Only one master function can be set at a time.
72 ;; You can restore any function's original function definition with
73 ;; elp-restore-function. The other instrument, restore, and reset
74 ;; functions are provided for symmetry.
76 ;; Here is a list of variable you can use to customize elp:
77 ;; elp-function-list
78 ;; elp-reset-after-results
79 ;; elp-sort-by-function
80 ;; elp-report-limit
82 ;; Here is a list of the interactive commands you can use:
83 ;; elp-instrument-function
84 ;; elp-restore-function
85 ;; elp-instrument-list
86 ;; elp-restore-list
87 ;; elp-instrument-package
88 ;; elp-restore-all
89 ;; elp-reset-function
90 ;; elp-reset-list
91 ;; elp-reset-all
92 ;; elp-set-master
93 ;; elp-unset-master
94 ;; elp-results
96 ;; Note that there are plenty of factors that could make the times
97 ;; reported unreliable, including the accuracy and granularity of your
98 ;; system clock, and the overhead spent in lisp calculating and
99 ;; recording the intervals. I figure the latter is pretty constant,
100 ;; so while the times may not be entirely accurate, I think they'll
101 ;; give you a good feel for the relative amount of work spent in the
102 ;; various lisp routines you are profiling. Note further that times
103 ;; are calculated using wall-clock time, so other system load will
104 ;; affect accuracy too.
106 ;;; Background:
108 ;; This program was inspired by the only two existing Emacs Lisp
109 ;; profilers that I'm aware of, Boaz Ben-Zvi's profile.el, and Root
110 ;; Boy Jim's profiler.el. Both were written for Emacs 18 and both were
111 ;; pretty good first shots at profiling, but I found that they didn't
112 ;; provide the functionality or interface that I wanted, so I wrote
113 ;; this. I've tested elp in XEmacs 19 and Emacs 19. There's no point
114 ;; in even trying to make this work with Emacs 18.
116 ;; Unlike previous profilers, elp uses Emacs 19's built-in function
117 ;; current-time to return interval times. This obviates the need for
118 ;; both an external C program and Emacs processes to communicate with
119 ;; such a program, and thus simplifies the package as a whole.
121 ;; TBD:
122 ;; Make this act like a real profiler, so that it records time spent
123 ;; in all branches of execution.
125 ;;; Code:
127 (eval-when-compile (require 'cl-lib))
129 ;; start of user configuration variables
130 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
132 (defgroup elp nil
133 "Emacs Lisp Profiler."
134 :group 'lisp)
136 (defcustom elp-function-list nil
137 "List of functions to profile.
138 Used by the command `elp-instrument-list'."
139 :type '(repeat function)
140 :group 'elp)
142 (defcustom elp-reset-after-results t
143 "Non-nil means reset all profiling info after results are displayed.
144 Results are displayed with the `elp-results' command."
145 :type 'boolean
146 :group 'elp)
148 (defcustom elp-sort-by-function 'elp-sort-by-total-time
149 "Non-nil specifies ELP results sorting function.
150 These functions are currently available:
152 `elp-sort-by-call-count' -- sort by the highest call count
153 `elp-sort-by-total-time' -- sort by the highest total time
154 `elp-sort-by-average-time' -- sort by the highest average times
156 You can write your own sort function. It should adhere to the
157 interface specified by the PREDICATE argument for `sort'.
158 Each \"element of LIST\" is really a 4 element vector where element 0 is
159 the call count, element 1 is the total time spent in the function,
160 element 2 is the average time spent in the function, and element 3 is
161 the symbol's name string."
162 :type 'function
163 :group 'elp)
165 (defcustom elp-report-limit 1
166 "Prevent some functions from being displayed in the results buffer.
167 If a number, no function that has been called fewer than that number
168 of times will be displayed in the output buffer. If nil, all
169 functions will be displayed."
170 :type '(choice integer
171 (const :tag "Show All" nil))
172 :group 'elp)
174 (defcustom elp-use-standard-output nil
175 "If non-nil, output to `standard-output' instead of a buffer."
176 :type 'boolean
177 :group 'elp)
179 (defcustom elp-recycle-buffers-p t
180 "If nil, don't recycle the `elp-results-buffer'.
181 In other words, a new unique buffer is create every time you run
182 \\[elp-results]."
183 :type 'boolean
184 :group 'elp)
187 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
188 ;; end of user configuration variables
191 (defvar elp-results-buffer "*ELP Profiling Results*"
192 "Buffer name for outputting profiling results.")
194 (defconst elp-timer-info-property 'elp-info
195 "ELP information property name.")
197 (defvar elp-record-p t
198 "Controls whether functions should record times or not.
199 This variable is set by the master function.")
201 (defvar elp-master nil
202 "Master function symbol.")
204 (defvar elp-not-profilable
205 ;; First, the functions used inside each instrumented function:
206 '(called-interactively-p
207 ;; Then the functions used by the above functions. I used
208 ;; (delq nil (mapcar (lambda (x) (and (symbolp x) (fboundp x) x))
209 ;; (aref (symbol-function 'elp-wrapper) 2)))
210 ;; to help me find this list.
211 error call-interactively apply current-time
212 ;; Andreas Politz reports problems profiling these (Bug#4233):
213 + byte-code-function-p functionp byte-code subrp
214 indirect-function fboundp)
215 "List of functions that cannot be profiled.
216 Those functions are used internally by the profiling code and profiling
217 them would thus lead to infinite recursion.")
219 (defun elp-profilable-p (fun)
220 (and (symbolp fun)
221 (fboundp fun)
222 (not (or (memq fun elp-not-profilable)
223 (keymapp fun)
224 (autoloadp (symbol-function fun)) ;FIXME: Why not just load it?
225 (special-form-p fun)))))
227 (defconst elp--advice-name 'ELP-instrumentation\ )
229 ;;;###autoload
230 (defun elp-instrument-function (funsym)
231 "Instrument FUNSYM for profiling.
232 FUNSYM must be a symbol of a defined function."
233 (interactive "aFunction to instrument: ")
234 (let* ((infovec (vector 0 0)))
235 ;; We cannot profile functions used internally during profiling.
236 (unless (elp-profilable-p funsym)
237 (error "ELP cannot profile the function: %s" funsym))
238 ;; The info vector data structure is a 2 element vector. The 0th
239 ;; element is the call-count, i.e. the total number of times this
240 ;; function has been entered. This value is bumped up on entry to
241 ;; the function so that non-local exists are still recorded. TBD:
242 ;; I haven't tested non-local exits at all, so no guarantees.
244 ;; The 1st element is the total amount of time in seconds that has
245 ;; been spent inside this function. This number is added to on
246 ;; function exit.
248 ;; Put the info vector on the property list.
249 (put funsym elp-timer-info-property infovec)
251 ;; Set the symbol's new profiling function definition to run
252 ;; ELP wrapper.
253 (advice-add funsym :around (elp--make-wrapper funsym)
254 `((name . ,elp--advice-name) (depth . -99)))))
256 (defun elp--instrumented-p (sym)
257 (advice-member-p elp--advice-name sym))
259 (defun elp-restore-function (funsym)
260 "Restore an instrumented function to its original definition.
261 Argument FUNSYM is the symbol of a defined function."
262 (interactive
263 (list
264 (intern
265 (completing-read "Function to restore: " obarray
266 #'elp--instrumented-p t))))
267 ;; If the function was the master, reset the master.
268 (if (eq funsym elp-master)
269 (setq elp-master nil
270 elp-record-p t))
272 ;; Zap the properties.
273 (put funsym elp-timer-info-property nil)
275 (advice-remove funsym elp--advice-name))
277 ;;;###autoload
278 (defun elp-instrument-list (&optional list)
279 "Instrument, for profiling, all functions in `elp-function-list'.
280 Use optional LIST if provided instead.
281 If called interactively, prompt for LIST in the minibuffer;
282 type \"nil\" to use `elp-function-list'."
283 (interactive "xList of functions to instrument: ")
284 (unless (listp list)
285 (signal 'wrong-type-argument (list 'listp list)))
286 (mapcar #'elp-instrument-function (or list elp-function-list)))
288 ;;;###autoload
289 (defun elp-instrument-package (prefix)
290 "Instrument for profiling, all functions which start with PREFIX.
291 For example, to instrument all ELP functions, do the following:
293 \\[elp-instrument-package] RET elp- RET"
294 (interactive
295 (list (completing-read "Prefix of package to instrument: "
296 obarray 'elp-profilable-p)))
297 (if (zerop (length prefix))
298 (error "Instrumenting all Emacs functions would render Emacs unusable"))
299 (elp-instrument-list
300 (mapcar
301 'intern
302 (all-completions prefix obarray 'elp-profilable-p))))
304 (defun elp-restore-list (&optional list)
305 "Restore the original definitions for all functions in `elp-function-list'.
306 Use optional LIST if provided instead."
307 (interactive "PList of functions to restore: ") ;FIXME: Doesn't work!?
308 (mapcar #'elp-restore-function (or list elp-function-list)))
310 (defun elp-restore-all ()
311 "Restore the original definitions of all functions being profiled."
312 (interactive)
313 (mapatoms #'elp-restore-function))
315 (defun elp-reset-function (funsym)
316 "Reset the profiling information for FUNSYM."
317 (interactive "aFunction to reset: ")
318 (let ((info (get funsym elp-timer-info-property)))
319 (or info
320 (error "%s is not instrumented for profiling" funsym))
321 (aset info 0 0) ;reset call counter
322 (aset info 1 0.0) ;reset total time
323 ;; don't muck with aref 2 as that is the old symbol definition
326 (defun elp-reset-list (&optional list)
327 "Reset the profiling information for all functions in `elp-function-list'.
328 Use optional LIST if provided instead."
329 (interactive "PList of functions to reset: ") ;FIXME: Doesn't work!?
330 (let ((list (or list elp-function-list)))
331 (mapcar 'elp-reset-function list)))
333 (defun elp-reset-all ()
334 "Reset the profiling information for all functions being profiled."
335 (interactive)
336 (mapatoms (lambda (sym)
337 (if (get sym elp-timer-info-property)
338 (elp-reset-function sym)))))
340 (defun elp-set-master (funsym)
341 "Set the master function for profiling."
342 (interactive
343 (list
344 (intern
345 (completing-read "Master function: " obarray
346 #'elp--instrumented-p
347 t nil nil (if elp-master (symbol-name elp-master))))))
348 ;; When there's a master function, recording is turned off by default.
349 (setq elp-master funsym
350 elp-record-p nil)
351 ;; Make sure master function is instrumented.
352 (or (elp--instrumented-p funsym)
353 (elp-instrument-function funsym)))
355 (defun elp-unset-master ()
356 "Unset the master function."
357 (interactive)
358 ;; When there's no master function, recording is turned on by default.
359 (setq elp-master nil
360 elp-record-p t))
363 (defsubst elp-elapsed-time (start end)
364 (float-time (time-subtract end start)))
366 (defun elp--make-wrapper (funsym)
367 "Make the piece of advice that instruments FUNSYM."
368 (lambda (func &rest args)
369 "This function has been instrumented for profiling by the ELP.
370 ELP is the Emacs Lisp Profiler. To restore the function to its
371 original definition, use \\[elp-restore-function] or \\[elp-restore-all]."
372 ;; turn on recording if this is the master function
373 (if (and elp-master
374 (eq funsym elp-master))
375 (setq elp-record-p t))
376 ;; get info vector and original function symbol
377 (let* ((info (get funsym elp-timer-info-property))
378 result)
379 (or func
380 (error "%s is not instrumented for profiling" funsym))
381 (if (not elp-record-p)
382 ;; when not recording, just call the original function symbol
383 ;; and return the results.
384 (setq result (apply func args))
385 ;; we are recording times
386 (let (enter-time exit-time)
387 ;; increment the call-counter
388 (cl-incf (aref info 0))
389 (setq enter-time (current-time)
390 result (apply func args)
391 exit-time (current-time))
392 ;; calculate total time in function
393 (cl-incf (aref info 1) (elp-elapsed-time enter-time exit-time))
395 ;; turn off recording if this is the master function
396 (if (and elp-master
397 (eq funsym elp-master))
398 (setq elp-record-p nil))
399 result)))
402 ;; shut the byte-compiler up
403 (defvar elp-field-len nil)
404 (defvar elp-cc-len nil)
405 (defvar elp-at-len nil)
406 (defvar elp-et-len nil)
408 (defun elp-sort-by-call-count (vec1 vec2)
409 ;; sort by highest call count. See `sort'.
410 (>= (aref vec1 0) (aref vec2 0)))
412 (defun elp-sort-by-total-time (vec1 vec2)
413 ;; sort by highest total time spent in function. See `sort'.
414 (>= (aref vec1 1) (aref vec2 1)))
416 (defun elp-sort-by-average-time (vec1 vec2)
417 ;; sort by highest average time spent in function. See `sort'.
418 (>= (aref vec1 2) (aref vec2 2)))
420 (defsubst elp-pack-number (number width)
421 ;; pack the NUMBER string into WIDTH characters, watching out for
422 ;; very small or large numbers
423 (if (<= (length number) width)
424 number
425 ;; check for very large or small numbers
426 (if (string-match "^\\(.*\\)\\(e[+-].*\\)$" number)
427 (concat (substring
428 (match-string 1 number)
430 (- width (match-end 2) (- (match-beginning 2)) 3))
431 "..."
432 (match-string 2 number))
433 (substring number 0 width))))
435 (defun elp-output-result (resultvec)
436 ;; output the RESULTVEC into the results buffer. RESULTVEC is a 4 or
437 ;; more element vector where aref 0 is the call count, aref 1 is the
438 ;; total time spent in the function, aref 2 is the average time
439 ;; spent in the function, and aref 3 is the symbol's string
440 ;; name. All other elements in the vector are ignored.
441 (let* ((cc (aref resultvec 0))
442 (tt (aref resultvec 1))
443 (at (aref resultvec 2))
444 (symname (aref resultvec 3))
445 callcnt totaltime avetime)
446 (setq callcnt (number-to-string cc)
447 totaltime (number-to-string tt)
448 avetime (number-to-string at))
449 ;; possibly prune the results
450 (if (and elp-report-limit
451 (numberp elp-report-limit)
452 (< cc elp-report-limit))
454 (elp-output-insert-symname symname)
455 (insert-char 32 (+ elp-field-len (- (length symname)) 2))
456 ;; print stuff out, formatting it nicely
457 (insert callcnt)
458 (insert-char 32 (+ elp-cc-len (- (length callcnt)) 2))
459 (let ((ttstr (elp-pack-number totaltime elp-et-len))
460 (atstr (elp-pack-number avetime elp-at-len)))
461 (insert ttstr)
462 (insert-char 32 (+ elp-et-len (- (length ttstr)) 2))
463 (insert atstr))
464 (insert "\n"))))
466 (defvar elp-results-symname-map
467 (let ((map (make-sparse-keymap)))
468 (define-key map [mouse-2] 'elp-results-jump-to-definition)
469 (define-key map [follow-link] 'mouse-face)
470 (define-key map "\C-m" 'elp-results-jump-to-definition)
471 map)
472 "Keymap used on the function name column." )
474 (defun elp-results-jump-to-definition (&optional event)
475 "Jump to the definition of the function under the point."
476 (interactive (list last-nonmenu-event))
477 (if event (posn-set-point (event-end event)))
478 (find-function (get-text-property (point) 'elp-symname)))
480 (defun elp-output-insert-symname (symname)
481 ;; Insert SYMNAME with text properties.
482 (insert (propertize symname
483 'elp-symname (intern symname)
484 'keymap elp-results-symname-map
485 'mouse-face 'highlight
486 'face 'link
487 'help-echo "mouse-2 or RET jumps to definition")))
489 ;;;###autoload
490 (defun elp-results ()
491 "Display current profiling results.
492 If `elp-reset-after-results' is non-nil, then current profiling
493 information for all instrumented functions is reset after results are
494 displayed."
495 (interactive)
496 (let ((curbuf (current-buffer))
497 (resultsbuf (if elp-recycle-buffers-p
498 (get-buffer-create elp-results-buffer)
499 (generate-new-buffer elp-results-buffer))))
500 (set-buffer resultsbuf)
501 (erase-buffer)
502 ;; get the length of the longest function name being profiled
503 (let* ((longest 0)
504 (title "Function Name")
505 (titlelen (length title))
506 (elp-field-len titlelen)
507 (cc-header "Call Count")
508 (elp-cc-len (length cc-header))
509 (et-header "Elapsed Time")
510 (elp-et-len (length et-header))
511 (at-header "Average Time")
512 (elp-at-len (length at-header))
513 (resvec '())
514 ) ; end let*
515 (mapatoms
516 (lambda (funsym)
517 (when (elp--instrumented-p funsym)
518 (let* ((info (get funsym elp-timer-info-property))
519 (symname (format "%s" funsym))
520 (cc (aref info 0))
521 (tt (aref info 1)))
522 (if (not info)
523 (insert "No profiling information found for: "
524 symname)
525 (setq longest (max longest (length symname)))
526 (push
527 (vector cc tt (if (zerop cc)
528 0.0 ;avoid arithmetic div-by-zero errors
529 (/ (float tt) (float cc)))
530 symname)
531 resvec))))))
532 ;; If printing to stdout, insert the header so it will print.
533 ;; Otherwise use header-line-format.
534 (setq elp-field-len (max titlelen longest))
535 (if (or elp-use-standard-output noninteractive)
536 (progn
537 (insert title)
538 (if (> longest titlelen)
539 (progn
540 (insert-char 32 (- longest titlelen))))
541 (insert " " cc-header " " et-header " " at-header "\n")
542 (insert-char ?= elp-field-len)
543 (insert " ")
544 (insert-char ?= elp-cc-len)
545 (insert " ")
546 (insert-char ?= elp-et-len)
547 (insert " ")
548 (insert-char ?= elp-at-len)
549 (insert "\n"))
550 (let ((column 0))
551 (setq header-line-format
552 (mapconcat
553 (lambda (title)
554 (prog1
555 (concat
556 (propertize " "
557 'display (list 'space :align-to column)
558 'face 'fixed-pitch)
559 title)
560 (setq column (+ column 2
561 (if (= column 0)
562 elp-field-len
563 (length title))))))
564 (list title cc-header et-header at-header) ""))))
565 ;; if sorting is enabled, then sort the results list. in either
566 ;; case, call elp-output-result to output the result in the
567 ;; buffer
568 (if elp-sort-by-function
569 (setq resvec (sort resvec elp-sort-by-function)))
570 (mapc 'elp-output-result resvec))
571 ;; now pop up results buffer
572 (set-buffer curbuf)
573 (pop-to-buffer resultsbuf)
574 ;; copy results to standard-output?
575 (if (or elp-use-standard-output noninteractive)
576 (princ (buffer-substring (point-min) (point-max)))
577 (goto-char (point-min)))
578 ;; reset profiling info if desired
579 (and elp-reset-after-results
580 (elp-reset-all))))
582 (defun elp-unload-function ()
583 "Unload the Emacs Lisp Profiler."
584 (elp-restore-all)
585 ;; continue standard unloading
586 nil)
588 (cl-defmethod loadhist-unload-element :before :extra "elp" ((x (head defun)))
589 "Un-instrument before unloading a function."
590 (elp-restore-function (cdr x)))
593 (provide 'elp)
595 ;;; elp.el ends here