("latin-1-prefix"): Change ~s to give \e,A'\e(B and
[emacs.git] / lisp / emacs-lisp / elp.el
blob308ab51ff61527377aaa1898c5f2f5e9716f14ed
1 ;;; elp.el --- Emacs Lisp Profiler
3 ;; Copyright (C) 1994,1995,1997,1998 Free Software Foundation, Inc.
5 ;; Author: 1994-1998 Barry A. Warsaw
6 ;; Maintainer: FSF
7 ;; Created: 26-Feb-1994
8 ;; Keywords: debugging lisp tools
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
27 ;;; Commentary:
29 ;; If you want to profile a bunch of functions, set elp-function-list
30 ;; to the list of symbols, then do a M-x elp-instrument-list. This
31 ;; hacks those functions so that profiling information is recorded
32 ;; whenever they are called. To print out the current results, use
33 ;; M-x elp-results. If you want output to go to standard-output
34 ;; instead of a separate buffer, setq elp-use-standard-output to
35 ;; non-nil. With elp-reset-after-results set to non-nil, profiling
36 ;; information will be reset whenever the results are displayed. You
37 ;; can also reset all profiling info at any time with M-x
38 ;; elp-reset-all.
40 ;; You can also instrument all functions in a package, provided that
41 ;; the package follows the GNU coding standard of a common textural
42 ;; prefix. Use M-x elp-instrument-package for this.
44 ;; If you want to sort the results, set elp-sort-by-function to some
45 ;; predicate function. The three most obvious choices are predefined:
46 ;; elp-sort-by-call-count, elp-sort-by-average-time, and
47 ;; elp-sort-by-total-time. Also, you can prune from the output, all
48 ;; functions that have been called fewer than a given number of times
49 ;; by setting elp-report-limit.
51 ;; Elp can instrument byte-compiled functions just as easily as
52 ;; interpreted functions, but it cannot instrument macros. However,
53 ;; when you redefine a function (e.g. with eval-defun), you'll need to
54 ;; re-instrument it with M-x elp-instrument-function. This will also
55 ;; reset profiling information for that function. Elp can handle
56 ;; interactive functions (i.e. commands), but of course any time spent
57 ;; idling for user prompts will show up in the timing results.
59 ;; You can also designate a `master' function. Profiling times will
60 ;; be gathered for instrumented functions only during execution of
61 ;; this master function. Thus, if you have some defuns like:
63 ;; (defun foo () (do-something-time-intensive))
64 ;; (defun bar () (foo))
65 ;; (defun baz () (bar) (foo))
67 ;; and you want to find out the amount of time spent in bar and foo,
68 ;; but only during execution of bar, make bar the master. The call of
69 ;; foo from baz will not add to foo's total timing sums. Use M-x
70 ;; elp-set-master and M-x elp-unset-master to utilize this feature.
71 ;; Only one master function can be set at a time.
73 ;; You can restore any function's original function definition with
74 ;; elp-restore-function. The other instrument, restore, and reset
75 ;; functions are provided for symmetry.
77 ;; Here is a list of variable you can use to customize elp:
78 ;; elp-function-list
79 ;; elp-reset-after-results
80 ;; elp-sort-by-function
81 ;; elp-report-limit
83 ;; Here is a list of the interactive commands you can use:
84 ;; elp-instrument-function
85 ;; elp-restore-function
86 ;; elp-instrument-list
87 ;; elp-restore-list
88 ;; elp-instrument-package
89 ;; elp-restore-all
90 ;; elp-reset-function
91 ;; elp-reset-list
92 ;; elp-reset-all
93 ;; elp-set-master
94 ;; elp-unset-master
95 ;; elp-results
97 ;; Note that there are plenty of factors that could make the times
98 ;; reported unreliable, including the accuracy and granularity of your
99 ;; system clock, and the overhead spent in lisp calculating and
100 ;; recording the intervals. I figure the latter is pretty constant,
101 ;; so while the times may not be entirely accurate, I think they'll
102 ;; give you a good feel for the relative amount of work spent in the
103 ;; various lisp routines you are profiling. Note further that times
104 ;; are calculated using wall-clock time, so other system load will
105 ;; affect accuracy too.
107 ;;; Background:
109 ;; This program was inspired by the only two existing Emacs Lisp
110 ;; profilers that I'm aware of, Boaz Ben-Zvi's profile.el, and Root
111 ;; Boy Jim's profiler.el. Both were written for Emacs 18 and both were
112 ;; pretty good first shots at profiling, but I found that they didn't
113 ;; provide the functionality or interface that I wanted, so I wrote
114 ;; this. I've tested elp in XEmacs 19 and Emacs 19. There's no point
115 ;; in even trying to make this work with Emacs 18.
117 ;; Unlike previous profilers, elp uses Emacs 19's built-in function
118 ;; current-time to return interval times. This obviates the need for
119 ;; both an external C program and Emacs processes to communicate with
120 ;; such a program, and thus simplifies the package as a whole.
122 ;; TBD:
123 ;; Make this act like a real profiler, so that it records time spent
124 ;; in all branches of execution.
126 ;;; Code:
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 you're own sort function. It should adhere to the
157 interface specified by the PRED argument for the `sort' defun. Each
158 \"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 "*Prevents 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 "*Non-nil says to output to `standard-output' instead of a buffer."
176 :type 'boolean
177 :group 'elp)
179 (defcustom elp-recycle-buffers-p t
180 "*Nil says to not 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-all-instrumented-list nil
198 "List of all functions currently being instrumented.")
200 (defvar elp-record-p t
201 "Controls whether functions should record times or not.
202 This variable is set by the master function.")
204 (defvar elp-master nil
205 "Master function symbol.")
208 ;;;###autoload
209 (defun elp-instrument-function (funsym)
210 "Instrument FUNSYM for profiling.
211 FUNSYM must be a symbol of a defined function."
212 (interactive "aFunction to instrument: ")
213 ;; restore the function. this is necessary to avoid infinite
214 ;; recursion of already instrumented functions (i.e. elp-wrapper
215 ;; calling elp-wrapper ad infinitum). it is better to simply
216 ;; restore the function than to throw an error. this will work
217 ;; properly in the face of eval-defun because if the function was
218 ;; redefined, only the timer info will be nil'd out since
219 ;; elp-restore-function is smart enough not to trash the new
220 ;; definition.
221 (elp-restore-function funsym)
222 (let* ((funguts (symbol-function funsym))
223 (infovec (vector 0 0 funguts))
224 (newguts '(lambda (&rest args))))
225 ;; we cannot profile macros
226 (and (eq (car-safe funguts) 'macro)
227 (error "ELP cannot profile macro: %s" funsym))
228 ;; TBD: at some point it might be better to load the autoloaded
229 ;; function instead of throwing an error. if we do this, then we
230 ;; probably want elp-instrument-package to be updated with the
231 ;; newly loaded list of functions. i'm not sure it's smart to do
232 ;; the autoload here, since that could have side effects, and
233 ;; elp-instrument-function is similar (in my mind) to defun-ish
234 ;; type functionality (i.e. it shouldn't execute the function).
235 (and (eq (car-safe funguts) 'autoload)
236 (error "ELP cannot profile autoloaded function: %s" funsym))
237 ;; put rest of newguts together
238 (if (commandp funsym)
239 (setq newguts (append newguts '((interactive)))))
240 (setq newguts (append newguts (list
241 (list 'elp-wrapper
242 (list 'quote funsym)
243 (list 'and
244 '(interactive-p)
245 (not (not (commandp funsym))))
246 'args))))
247 ;; to record profiling times, we set the symbol's function
248 ;; definition so that it runs the elp-wrapper function with the
249 ;; function symbol as an argument. We place the old function
250 ;; definition on the info vector.
252 ;; The info vector data structure is a 3 element vector. The 0th
253 ;; element is the call-count, i.e. the total number of times this
254 ;; function has been entered. This value is bumped up on entry to
255 ;; the function so that non-local exists are still recorded. TBD:
256 ;; I haven't tested non-local exits at all, so no guarantees.
258 ;; The 1st element is the total amount of time in usecs that have
259 ;; been spent inside this function. This number is added to on
260 ;; function exit.
262 ;; The 2nd element is the old function definition list. This gets
263 ;; funcall'd in between start/end time retrievals. I believe that
264 ;; this lets us profile even byte-compiled functions.
266 ;; put the info vector on the property list
267 (put funsym elp-timer-info-property infovec)
269 ;; set the symbol's new profiling function definition to run
270 ;; elp-wrapper
271 (fset funsym newguts)
273 ;; add this function to the instrumentation list
274 (or (memq funsym elp-all-instrumented-list)
275 (setq elp-all-instrumented-list
276 (cons funsym elp-all-instrumented-list)))
279 ;;;###autoload
280 (defun elp-restore-function (funsym)
281 "Restore an instrumented function to its original definition.
282 Argument FUNSYM is the symbol of a defined function."
283 (interactive "aFunction to restore: ")
284 (let ((info (get funsym elp-timer-info-property)))
285 ;; delete the function from the all instrumented list
286 (setq elp-all-instrumented-list
287 (delq funsym elp-all-instrumented-list))
289 ;; if the function was the master, reset the master
290 (if (eq funsym elp-master)
291 (setq elp-master nil
292 elp-record-p t))
294 ;; zap the properties
295 (put funsym elp-timer-info-property nil)
297 ;; restore the original function definition, but if the function
298 ;; wasn't instrumented do nothing. we do this after the above
299 ;; because its possible the function got un-instrumented due to
300 ;; circumstances beyond our control. Also, check to make sure
301 ;; that the current function symbol points to elp-wrapper. If
302 ;; not, then the user probably did an eval-defun, or loaded a
303 ;; byte-compiled version, while the function was instrumented and
304 ;; we don't want to destroy the new definition. can it ever be
305 ;; the case that a lisp function can be compiled instrumented?
306 (and info
307 (functionp funsym)
308 (not (byte-code-function-p (symbol-function funsym)))
309 (assq 'elp-wrapper (symbol-function funsym))
310 (fset funsym (aref info 2)))))
312 ;;;###autoload
313 (defun elp-instrument-list (&optional list)
314 "Instrument for profiling, all functions in `elp-function-list'.
315 Use optional LIST if provided instead."
316 (interactive "PList of functions to instrument: ")
317 (let ((list (or list elp-function-list)))
318 (mapcar 'elp-instrument-function list)))
320 ;;;###autoload
321 (defun elp-instrument-package (prefix)
322 "Instrument for profiling, all functions which start with PREFIX.
323 For example, to instrument all ELP functions, do the following:
325 \\[elp-instrument-package] RET elp- RET"
326 (interactive "sPrefix of package to instrument: ")
327 (elp-instrument-list
328 (mapcar
329 'intern
330 (all-completions
331 prefix obarray
332 (function
333 (lambda (sym)
334 (and (fboundp sym)
335 (not (memq (car-safe (symbol-function sym)) '(autoload macro))))
337 ))))
339 (defun elp-restore-list (&optional list)
340 "Restore the original definitions for all functions in `elp-function-list'.
341 Use optional LIST if provided instead."
342 (interactive "PList of functions to restore: ")
343 (let ((list (or list elp-function-list)))
344 (mapcar 'elp-restore-function list)))
346 (defun elp-restore-all ()
347 "Restores the original definitions of all functions being profiled."
348 (interactive)
349 (elp-restore-list elp-all-instrumented-list))
352 (defun elp-reset-function (funsym)
353 "Reset the profiling information for FUNSYM."
354 (interactive "aFunction to reset: ")
355 (let ((info (get funsym elp-timer-info-property)))
356 (or info
357 (error "%s is not instrumented for profiling." funsym))
358 (aset info 0 0) ;reset call counter
359 (aset info 1 0.0) ;reset total time
360 ;; don't muck with aref 2 as that is the old symbol definition
363 (defun elp-reset-list (&optional list)
364 "Reset the profiling information for all functions in `elp-function-list'.
365 Use optional LIST if provided instead."
366 (interactive "PList of functions to reset: ")
367 (let ((list (or list elp-function-list)))
368 (mapcar 'elp-reset-function list)))
370 (defun elp-reset-all ()
371 "Reset the profiling information for all functions being profiled."
372 (interactive)
373 (elp-reset-list elp-all-instrumented-list))
375 (defun elp-set-master (funsym)
376 "Set the master function for profiling."
377 (interactive "aMaster function: ")
378 ;; when there's a master function, recording is turned off by
379 ;; default
380 (setq elp-master funsym
381 elp-record-p nil)
382 ;; make sure master function is instrumented
383 (or (memq funsym elp-all-instrumented-list)
384 (elp-instrument-function funsym)))
386 (defun elp-unset-master ()
387 "Unsets the master function."
388 (interactive)
389 ;; when there's no master function, recording is turned on by default.
390 (setq elp-master nil
391 elp-record-p t))
394 (defsubst elp-elapsed-time (start end)
395 (+ (* (- (car end) (car start)) 65536.0)
396 (- (car (cdr end)) (car (cdr start)))
397 (/ (- (car (cdr (cdr end))) (car (cdr (cdr start)))) 1000000.0)))
399 (defun elp-wrapper (funsym interactive-p args)
400 "This function has been instrumented for profiling by the ELP.
401 ELP is the Emacs Lisp Profiler. To restore the function to its
402 original definition, use \\[elp-restore-function] or \\[elp-restore-all]."
403 ;; turn on recording if this is the master function
404 (if (and elp-master
405 (eq funsym elp-master))
406 (setq elp-record-p t))
407 ;; get info vector and original function symbol
408 (let* ((info (get funsym elp-timer-info-property))
409 (func (aref info 2))
410 result)
411 (or func
412 (error "%s is not instrumented for profiling." funsym))
413 (if (not elp-record-p)
414 ;; when not recording, just call the original function symbol
415 ;; and return the results.
416 (setq result
417 (if interactive-p
418 (call-interactively func)
419 (apply func args)))
420 ;; we are recording times
421 (let (enter-time exit-time)
422 ;; increment the call-counter
423 (aset info 0 (1+ (aref info 0)))
424 ;; now call the old symbol function, checking to see if it
425 ;; should be called interactively. make sure we return the
426 ;; correct value
427 (if interactive-p
428 (setq enter-time (current-time)
429 result (call-interactively func)
430 exit-time (current-time))
431 (setq enter-time (current-time)
432 result (apply func args)
433 exit-time (current-time)))
434 ;; calculate total time in function
435 (aset info 1 (+ (aref info 1) (elp-elapsed-time enter-time exit-time)))
437 ;; turn off recording if this is the master function
438 (if (and elp-master
439 (eq funsym elp-master))
440 (setq elp-record-p nil))
441 result))
444 ;; shut the byte-compiler up
445 (defvar elp-field-len nil)
446 (defvar elp-cc-len nil)
447 (defvar elp-at-len nil)
448 (defvar elp-et-len nil)
450 (defun elp-sort-by-call-count (vec1 vec2)
451 ;; sort by highest call count. See `sort'.
452 (>= (aref vec1 0) (aref vec2 0)))
454 (defun elp-sort-by-total-time (vec1 vec2)
455 ;; sort by highest total time spent in function. See `sort'.
456 (>= (aref vec1 1) (aref vec2 1)))
458 (defun elp-sort-by-average-time (vec1 vec2)
459 ;; sort by highest average time spent in function. See `sort'.
460 (>= (aref vec1 2) (aref vec2 2)))
462 (defsubst elp-pack-number (number width)
463 ;; pack the NUMBER string into WIDTH characters, watching out for
464 ;; very small or large numbers
465 (if (<= (length number) width)
466 number
467 ;; check for very large or small numbers
468 (if (string-match "^\\(.*\\)\\(e[+-].*\\)$" number)
469 (concat (substring
470 (substring number (match-beginning 1) (match-end 1))
472 (- width (match-end 2) (- (match-beginning 2)) 3))
473 "..."
474 (substring number (match-beginning 2) (match-end 2)))
475 (concat (substring number 0 width)))))
477 (defun elp-output-result (resultvec)
478 ;; output the RESULTVEC into the results buffer. RESULTVEC is a 4 or
479 ;; more element vector where aref 0 is the call count, aref 1 is the
480 ;; total time spent in the function, aref 2 is the average time
481 ;; spent in the function, and aref 3 is the symbol's string
482 ;; name. All other elements in the vector are ignored.
483 (let* ((cc (aref resultvec 0))
484 (tt (aref resultvec 1))
485 (at (aref resultvec 2))
486 (symname (aref resultvec 3))
487 callcnt totaltime avetime)
488 (setq callcnt (number-to-string cc)
489 totaltime (number-to-string tt)
490 avetime (number-to-string at))
491 ;; possibly prune the results
492 (if (and elp-report-limit
493 (numberp elp-report-limit)
494 (< cc elp-report-limit))
496 (insert symname)
497 (insert-char 32 (+ elp-field-len (- (length symname)) 2))
498 ;; print stuff out, formatting it nicely
499 (insert callcnt)
500 (insert-char 32 (+ elp-cc-len (- (length callcnt)) 2))
501 (let ((ttstr (elp-pack-number totaltime elp-et-len))
502 (atstr (elp-pack-number avetime elp-at-len)))
503 (insert ttstr)
504 (insert-char 32 (+ elp-et-len (- (length ttstr)) 2))
505 (insert atstr))
506 (insert "\n"))))
508 ;;;###autoload
509 (defun elp-results ()
510 "Display current profiling results.
511 If `elp-reset-after-results' is non-nil, then current profiling
512 information for all instrumented functions are reset after results are
513 displayed."
514 (interactive)
515 (let ((curbuf (current-buffer))
516 (resultsbuf (if elp-recycle-buffers-p
517 (get-buffer-create elp-results-buffer)
518 (generate-new-buffer elp-results-buffer))))
519 (set-buffer resultsbuf)
520 (erase-buffer)
521 (beginning-of-buffer)
522 ;; get the length of the longest function name being profiled
523 (let* ((longest 0)
524 (title "Function Name")
525 (titlelen (length title))
526 (elp-field-len titlelen)
527 (cc-header "Call Count")
528 (elp-cc-len (length cc-header))
529 (et-header "Elapsed Time")
530 (elp-et-len (length et-header))
531 (at-header "Average Time")
532 (elp-at-len (length at-header))
533 (resvec
534 (mapcar
535 (function
536 (lambda (funsym)
537 (let* ((info (get funsym elp-timer-info-property))
538 (symname (format "%s" funsym))
539 (cc (aref info 0))
540 (tt (aref info 1)))
541 (if (not info)
542 (insert "No profiling information found for: "
543 symname)
544 (setq longest (max longest (length symname)))
545 (vector cc tt (if (zerop cc)
546 0.0 ;avoid arithmetic div-by-zero errors
547 (/ (float tt) (float cc)))
548 symname)))))
549 elp-all-instrumented-list))
550 ) ; end let*
551 (insert title)
552 (if (> longest titlelen)
553 (progn
554 (insert-char 32 (- longest titlelen))
555 (setq elp-field-len longest)))
556 (insert " " cc-header " " et-header " " at-header "\n")
557 (insert-char ?= elp-field-len)
558 (insert " ")
559 (insert-char ?= elp-cc-len)
560 (insert " ")
561 (insert-char ?= elp-et-len)
562 (insert " ")
563 (insert-char ?= elp-at-len)
564 (insert "\n")
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 (mapcar '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 ;; reset profiling info if desired
578 (and elp-reset-after-results
579 (elp-reset-all))))
581 (provide 'elp)
583 ;; elp.el ends here