(pp-to-string): Don't use emacs-lisp-mode.
[bpt/emacs.git] / lisp / emacs-lisp / elp.el
1 ;;; elp.el --- Emacs Lisp Profiler
2
3 ;; Copyright (C) 1994 Free Software Foundation, Inc.
4
5 ;; Author: 1994 Barry A. Warsaw <bwarsaw@cnri.reston.va.us>
6 ;; Maintainer: tools-help@anthem.nlm.nih.gov
7 ;; Created: 26-Feb-1994
8 ;; Version: 2.23
9 ;; Last Modified: 1994/12/28 22:39:31
10 ;; Keywords: Emacs Lisp Profile Timing
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to
26 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
27
28 ;;; Commentary:
29 ;;
30 ;; If you want to profile a bunch of functions, set elp-function-list
31 ;; to the list of symbols, then do a M-x elp-instrument-list. This
32 ;; hacks those functions so that profiling information is recorded
33 ;; whenever they are called. To print out the current results, use
34 ;; M-x elp-results. With elp-reset-after-results set to non-nil,
35 ;; profiling information will be reset whenever the results are
36 ;; displayed. You can also reset all profiling info at any time with
37 ;; M-x elp-reset-all.
38 ;;
39 ;; You can also instrument all functions in a package, provided that
40 ;; the package follows the GNU coding standard of a common textural
41 ;; prefix. Use M-x elp-instrument-package for this.
42 ;;
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.
49 ;;
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.
57 ;;
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:
61 ;;
62 ;; (defun foo () (do-something-time-intensive))
63 ;; (defun bar () (foo))
64 ;; (defun baz () (bar) (foo))
65 ;;
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.
71
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.
75
76 ;; Note that there are plenty of factors that could make the times
77 ;; reported unreliable, including the accuracy and granularity of your
78 ;; system clock, and the overhead spent in lisp calculating and
79 ;; recording the intervals. The latter I figure is pretty constant
80 ;; so, while the times may not be entirely accurate, I think they'll
81 ;; give you a good feel for the relative amount of work spent in the
82 ;; various lisp routines you are profiling. Note further that times
83 ;; are calculated using wall-clock time, so other system load will
84 ;; affect accuracy too.
85
86 ;; Here is a list of variable you can use to customize elp:
87 ;; elp-function-list
88 ;; elp-reset-after-results
89 ;; elp-sort-by-function
90 ;; elp-report-limit
91 ;;
92 ;; Here is a list of the interactive commands you can use:
93 ;; elp-instrument-function
94 ;; elp-restore-function
95 ;; elp-instrument-list
96 ;; elp-restore-list
97 ;; elp-instrument-package
98 ;; elp-restore-all
99 ;; elp-reset-function
100 ;; elp-reset-list
101 ;; elp-reset-all
102 ;; elp-set-master
103 ;; elp-unset-master
104 ;; elp-results
105 ;; elp-submit-bug-report
106
107 ;; Note that there are plenty of factors that could make the times
108 ;; reported unreliable, including the accuracy and granularity of your
109 ;; system clock, and the overhead spent in lisp calculating and
110 ;; recording the intervals. I figure the latter is pretty constant,
111 ;; so while the times may not be entirely accurate, I think they'll
112 ;; give you a good feel for the relative amount of work spent in the
113 ;; various lisp routines you are profiling. Note further that times
114 ;; are calculated using wall-clock time, so other system load will
115 ;; affect accuracy too. You cannot profile anything longer than ~18
116 ;; hours since I throw away the most significant 16 bits of seconds
117 ;; returned by current-time: 2^16 == 65536 seconds == ~1092 minutes ==
118 ;; ~18 hours. I doubt you will ever want to profile stuff on the
119 ;; order of 18 hours anyway.
120
121 ;;; Background:
122
123 ;; This program is based on the only two existing Emacs Lisp profilers
124 ;; that I'm aware of, Boaz Ben-Zvi's profile.el, and Root Boy Jim's
125 ;; profiler.el. Both were written for Emacs 18 and both were pretty
126 ;; good first shots at profiling, but I found that they didn't provide
127 ;; the functionality or interface that I wanted. So I wrote this.
128 ;; I've tested elp in GNU Emacs 19 and in GNU XEmacs. There's no
129 ;; point in even trying to make this work with Emacs 18.
130
131 ;; Unlike previous profilers, elp uses Emacs 19's built-in function
132 ;; current-time to return interval times. This obviates the need for
133 ;; both an external C program and Emacs processes to communicate with
134 ;; such a program, and thus simplifies the package as a whole.
135
136 ;;; Code:
137
138 \f
139 ;; start user configuration variables
140 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
141
142 (defvar elp-function-list nil
143 "*List of function to profile.")
144
145 (defvar elp-reset-after-results t
146 "*Non-nil means reset all profiling info after results are displayed.
147 Results are displayed with the `elp-results' command.")
148
149 (defvar elp-sort-by-function nil
150 "*Non-nil specifies elp results sorting function.
151 These functions are currently available:
152
153 elp-sort-by-call-count -- sort by the highest call count
154 elp-sort-by-total-time -- sort by the highest total time
155 elp-sort-by-average-time -- sort by the highest average times
156
157 You can write you're own sort function. It should adhere to the
158 interface specified by the PRED argument for the `sort' defun. Each
159 \"element of LIST\" is really a 4 element vector where element 0 is
160 the call count, element 1 is the total time spent in the function,
161 element 2 is the average time spent in the function, and element 3 is
162 the symbol's name string.")
163
164 (defvar elp-report-limit nil
165 "*Prevents some functions from being displayed in the results buffer.
166 If a number, no function that has been called fewer than that number
167 of times will be displayed in the output buffer. If nil, all
168 functions will be displayed.")
169
170
171 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
172 ;; end user configuration variables
173
174 \f
175 (defconst elp-version "2.23"
176 "ELP version number.")
177
178 (defconst elp-help-address "tools-help@anthem.nlm.nih.gov"
179 "Address accepting submissions of bug reports and questions.")
180
181 (defvar elp-results-buffer "*ELP Profiling Results*"
182 "Buffer name for outputting profiling results.")
183
184 (defconst elp-timer-info-property 'elp-info
185 "ELP information property name.")
186
187 (defvar elp-all-instrumented-list nil
188 "List of all functions currently being instrumented.")
189
190 (defvar elp-record-p t
191 "Controls whether functions should record times or not.
192 This variable is set by the master function.")
193
194 (defvar elp-master nil
195 "Master function symbol.")
196
197 \f
198 ;;;###autoload
199 (defun elp-instrument-function (funsym)
200 "Instrument FUNSYM for profiling.
201 FUNSYM must be a symbol of a defined function."
202 (interactive "aFunction to instrument: ")
203 ;; TBD what should we do if the function is already instrumented???
204 (let* ((funguts (symbol-function funsym))
205 (infovec (vector 0 0 funguts))
206 (newguts '(lambda (&rest args))))
207 ;; we cannot profile macros
208 (and (eq (car-safe funguts) 'macro)
209 (error "ELP cannot profile macro %s" funsym))
210 ;; put rest of newguts together
211 (if (commandp funsym)
212 (setq newguts (append newguts '((interactive)))))
213 (setq newguts (append newguts (list
214 (list 'elp-wrapper
215 (list 'quote funsym)
216 (list 'and
217 '(interactive-p)
218 (not (not (commandp funsym))))
219 'args))))
220 ;; to record profiling times, we set the symbol's function
221 ;; definition so that it runs the elp-wrapper function with the
222 ;; function symbol as an argument. We place the old function
223 ;; definition on the info vector.
224 ;;
225 ;; The info vector data structure is a 3 element vector. The 0th
226 ;; element is the call-count, i.e. the total number of times this
227 ;; function has been entered. This value is bumped up on entry to
228 ;; the function so that non-local exists are still recorded. TBD:
229 ;; I haven't tested non-local exits at all, so no guarantees.
230 ;;
231 ;; The 1st element is the total amount of time in usecs that have
232 ;; been spent inside this function. This number is added to on
233 ;; function exit.
234 ;;
235 ;; The 2nd element is the old function definition list. This gets
236 ;; funcall'd in between start/end time retrievals. I believe that
237 ;; this lets us profile even byte-compiled functions.
238
239 ;; put the info vector on the property list
240 (put funsym elp-timer-info-property infovec)
241
242 ;; set the symbol's new profiling function definition to run
243 ;; elp-wrapper
244 (fset funsym newguts)
245
246 ;; add this function to the instrumentation list
247 (or (memq funsym elp-all-instrumented-list)
248 (setq elp-all-instrumented-list
249 (cons funsym elp-all-instrumented-list)))
250 ))
251
252 ;;;###autoload
253 (defun elp-restore-function (funsym)
254 "Restore an instrumented function to its original definition.
255 Argument FUNSYM is the symbol of a defined function."
256 (interactive "aFunction to restore: ")
257 (let ((info (get funsym elp-timer-info-property)))
258 ;; delete the function from the all instrumented list
259 (setq elp-all-instrumented-list
260 (delq funsym elp-all-instrumented-list))
261
262 ;; if the function was the master, reset the master
263 (if (eq funsym elp-master)
264 (setq elp-master nil
265 elp-record-p t))
266
267 ;; zap the properties
268 (put funsym elp-timer-info-property nil)
269
270 ;; restore the original function definition, but if the function
271 ;; wasn't instrumented do nothing. we do this after the above
272 ;; because its possible the function got un-instrumented due to
273 ;; circumstances beyond our control. Also, check to make sure
274 ;; that the current function symbol points to elp-wrapper. If
275 ;; not, then the user probably did an eval-defun while the
276 ;; function was instrumented and we don't want to destroy the new
277 ;; definition.
278 (and info
279 (assq 'elp-wrapper (symbol-function funsym))
280 (fset funsym (aref info 2)))))
281
282 ;;;###autoload
283 (defun elp-instrument-list (&optional list)
284 "Instrument for profiling, all functions in `elp-function-list'.
285 Use optional LIST if provided instead."
286 (interactive "PList of functions to instrument: ")
287 (let ((list (or list elp-function-list)))
288 (mapcar 'elp-instrument-function list)))
289
290 ;;;###autoload
291 (defun elp-instrument-package (prefix)
292 "Instrument for profiling, all functions which start with PREFIX.
293 For example, to instrument all ELP functions, do the following:
294
295 \\[elp-instrument-package] RET elp- RET"
296 (interactive "sPrefix of package to instrument: ")
297 (elp-instrument-list
298 (mapcar 'intern (all-completions prefix obarray
299 (function
300 (lambda (sym)
301 (and (fboundp sym)
302 (not (eq (car-safe
303 (symbol-function sym))
304 'macro)))))))))
305
306 (defun elp-restore-list (&optional list)
307 "Restore the original definitions for all functions in `elp-function-list'.
308 Use optional LIST if provided instead."
309 (interactive "PList of functions to restore: ")
310 (let ((list (or list elp-function-list)))
311 (mapcar 'elp-restore-function list)))
312
313 (defun elp-restore-all ()
314 "Restores the original definitions of all functions being profiled."
315 (interactive)
316 (elp-restore-list elp-all-instrumented-list))
317
318 \f
319 (defun elp-reset-function (funsym)
320 "Reset the profiling information for FUNSYM."
321 (interactive "aFunction to reset: ")
322 (let ((info (get funsym elp-timer-info-property)))
323 (or info
324 (error "%s is not instrumented for profiling." funsym))
325 (aset info 0 0) ;reset call counter
326 (aset info 1 0.0) ;reset total time
327 ;; don't muck with aref 2 as that is the old symbol definition
328 ))
329
330 (defun elp-reset-list (&optional list)
331 "Reset the profiling information for all functions in `elp-function-list'.
332 Use optional LIST if provided instead."
333 (interactive "PList of functions to reset: ")
334 (let ((list (or list elp-function-list)))
335 (mapcar 'elp-reset-function list)))
336
337 (defun elp-reset-all ()
338 "Reset the profiling information for all functions being profiled."
339 (interactive)
340 (elp-reset-list elp-all-instrumented-list))
341
342 (defun elp-set-master (funsym)
343 "Set the master function for profiling."
344 (interactive "aMaster function: ")
345 ;; when there's a master function, recording is turned off by
346 ;; default
347 (setq elp-master funsym
348 elp-record-p nil)
349 ;; make sure master function is instrumented
350 (or (memq funsym elp-all-instrumented-list)
351 (elp-instrument-function funsym)))
352
353 (defun elp-unset-master ()
354 "Unsets the master function."
355 (interactive)
356 ;; when there's no master function, recording is turned on by default.
357 (setq elp-master nil
358 elp-record-p t))
359
360 \f
361 (defsubst elp-get-time ()
362 ;; get current time in seconds and microseconds. I throw away the
363 ;; most significant 16 bits of seconds since I doubt we'll ever want
364 ;; to profile lisp on the order of 18 hours. See notes at top of file.
365 (let ((now (current-time)))
366 (+ (float (nth 1 now)) (/ (float (nth 2 now)) 1000000.0))))
367
368 (defun elp-wrapper (funsym interactive-p 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 (func (aref info 2))
379 result)
380 (or func
381 (error "%s is not instrumented for profiling." funsym))
382 (if (not elp-record-p)
383 ;; when not recording, just call the original function symbol
384 ;; and return the results.
385 (setq result
386 (if interactive-p
387 (call-interactively func)
388 (apply func args)))
389 ;; we are recording times
390 (let ((enter-time (elp-get-time)))
391 ;; increment the call-counter
392 (aset info 0 (1+ (aref info 0)))
393 ;; now call the old symbol function, checking to see if it
394 ;; should be called interactively. make sure we return the
395 ;; correct value
396 (setq result
397 (if interactive-p
398 (call-interactively func)
399 (apply func args)))
400 ;; calculate total time in function
401 (aset info 1 (+ (aref info 1) (- (elp-get-time) enter-time)))
402 ))
403 ;; turn off recording if this is the master function
404 (if (and elp-master
405 (eq funsym elp-master))
406 (setq elp-record-p nil))
407 result))
408
409 \f
410 ;; shut the byte-compiler up
411 (defvar elp-field-len nil)
412 (defvar elp-cc-len nil)
413 (defvar elp-at-len nil)
414 (defvar elp-et-len nil)
415
416 (defun elp-sort-by-call-count (vec1 vec2)
417 ;; sort by highest call count. See `sort'.
418 (>= (aref vec1 0) (aref vec2 0)))
419
420 (defun elp-sort-by-total-time (vec1 vec2)
421 ;; sort by highest total time spent in function. See `sort'.
422 (>= (aref vec1 1) (aref vec2 1)))
423
424 (defun elp-sort-by-average-time (vec1 vec2)
425 ;; sort by highest average time spent in function. See `sort'.
426 (>= (aref vec1 2) (aref vec2 2)))
427
428 (defsubst elp-pack-number (number width)
429 ;; pack the NUMBER string into WIDTH characters, watching out for
430 ;; very small or large numbers
431 (if (<= (length number) width)
432 number
433 ;; check for very large or small numbers
434 (if (string-match "^\\(.*\\)\\(e[+-].*\\)$" number)
435 (concat (substring
436 (substring number (match-beginning 1) (match-end 1))
437 0
438 (- width (match-end 2) (- (match-beginning 2)) 3))
439 "..."
440 (substring number (match-beginning 2) (match-end 2)))
441 (concat (substring number 0 width)))))
442
443 (defun elp-output-result (resultvec)
444 ;; output the RESULTVEC into the results buffer. RESULTVEC is a 4 or
445 ;; more element vector where aref 0 is the call count, aref 1 is the
446 ;; total time spent in the function, aref 2 is the average time
447 ;; spent in the function, and aref 3 is the symbol's string
448 ;; name. All other elements in the vector are ignored.
449 (let* ((cc (aref resultvec 0))
450 (tt (aref resultvec 1))
451 (at (aref resultvec 2))
452 (symname (aref resultvec 3))
453 callcnt totaltime avetime)
454 (setq callcnt (number-to-string cc)
455 totaltime (number-to-string tt)
456 avetime (number-to-string at))
457 ;; possibly prune the results
458 (if (and elp-report-limit
459 (numberp elp-report-limit)
460 (< cc elp-report-limit))
461 nil
462 (insert symname)
463 (insert-char 32 (+ elp-field-len (- (length symname)) 2))
464 ;; print stuff out, formatting it nicely
465 (insert callcnt)
466 (insert-char 32 (+ elp-cc-len (- (length callcnt)) 2))
467 (let ((ttstr (elp-pack-number totaltime elp-et-len))
468 (atstr (elp-pack-number avetime elp-at-len)))
469 (insert ttstr)
470 (insert-char 32 (+ elp-et-len (- (length ttstr)) 2))
471 (insert atstr))
472 (insert "\n"))))
473
474 ;;;###autoload
475 (defun elp-results ()
476 "Display current profiling results.
477 If `elp-reset-after-results' is non-nil, then current profiling
478 information for all instrumented functions are reset after results are
479 displayed."
480 (interactive)
481 (let ((curbuf (current-buffer))
482 (resultsbuf (get-buffer-create elp-results-buffer)))
483 (set-buffer resultsbuf)
484 (erase-buffer)
485 (beginning-of-buffer)
486 ;; get the length of the longest function name being profiled
487 (let* ((longest 0)
488 (title "Function Name")
489 (titlelen (length title))
490 (elp-field-len titlelen)
491 (cc-header "Call Count")
492 (elp-cc-len (length cc-header))
493 (et-header "Elapsed Time")
494 (elp-et-len (length et-header))
495 (at-header "Average Time")
496 (elp-at-len (length at-header))
497 (resvec
498 (mapcar
499 (function
500 (lambda (funsym)
501 (let* ((info (get funsym elp-timer-info-property))
502 (symname (format "%s" funsym))
503 (cc (aref info 0))
504 (tt (aref info 1)))
505 (if (not info)
506 (insert "No profiling information found for: "
507 symname)
508 (setq longest (max longest (length symname)))
509 (vector cc tt (if (zerop cc)
510 0.0 ;avoid arithmetic div-by-zero errors
511 (/ (float tt) (float cc)))
512 symname)))))
513 elp-all-instrumented-list))
514 ) ; end let*
515 (insert title)
516 (if (> longest titlelen)
517 (progn
518 (insert-char 32 (- longest titlelen))
519 (setq elp-field-len longest)))
520 (insert " " cc-header " " et-header " " at-header "\n")
521 (insert-char ?= elp-field-len)
522 (insert " ")
523 (insert-char ?= elp-cc-len)
524 (insert " ")
525 (insert-char ?= elp-et-len)
526 (insert " ")
527 (insert-char ?= elp-at-len)
528 (insert "\n")
529 ;; if sorting is enabled, then sort the results list. in either
530 ;; case, call elp-output-result to output the result in the
531 ;; buffer
532 (if elp-sort-by-function
533 (setq resvec (sort resvec elp-sort-by-function)))
534 (mapcar 'elp-output-result resvec))
535 ;; now pop up results buffer
536 (set-buffer curbuf)
537 (pop-to-buffer resultsbuf)
538 ;; reset profiling info if desired
539 (and elp-reset-after-results
540 (elp-reset-all))))
541
542 \f
543 (eval-when-compile
544 (require 'reporter))
545
546 ;;;###autoload
547 (defun elp-submit-bug-report ()
548 "Submit via mail, a bug report on elp."
549 (interactive)
550 (and
551 (y-or-n-p "Do you want to submit a report on elp? ")
552 (require 'reporter)
553 (reporter-submit-bug-report
554 elp-help-address (concat "elp " elp-version)
555 '(elp-report-limit
556 elp-reset-after-results
557 elp-sort-by-function))))
558
559 \f
560 (provide 'elp)
561
562 ;; elp.el ends here