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