]> code.delx.au - gnu-emacs/blobdiff - lisp/emacs-lisp/elp.el
(echo_char): Use KEY_DESCRIPTION_SIZE to check free
[gnu-emacs] / lisp / emacs-lisp / elp.el
index 9564f8a823c9e695c06446a5f5563a66ad0be136..ea44a65e4512eeccba4d3d5f00927f85d9be5a65 100644 (file)
 ;;; elp.el --- Emacs Lisp Profiler
 
-;; Author: 1994 Barry A. Warsaw, Century Computing, Inc. <bwarsaw@cen.com>
-;; Maintainer:    bwarsaw@cen.com
+;; Copyright (C) 1994,1995,1997,1998 Free Software Foundation, Inc.
+
+;; Author:        1994-1998 Barry A. Warsaw
+;; Maintainer:    tools-help@python.org
 ;; Created:       26-Feb-1994
-;; Version:       2.11
-;; Last Modified: 1994/06/06 22:38:07
-;; Keywords:      Emacs Lisp Profile Timing
+;; Version:       3.2
+;; Keywords:      debugging lisp tools
 
-;; Copyright (C) 1994 Barry A. Warsaw
+;; This file is part of GNU Emacs.
 
-;; This file is not yet part of GNU Emacs.
-;;
-;; This program is free software; you can redistribute it and/or modify
+;; GNU Emacs is free software; you can redistribute it and/or modify
 ;; it under the terms of the GNU General Public License as published by
-;; the Free Software Foundation; either version 2 of the License, or
-;; (at your option) any later version.
-;; 
-;; This program is distributed in the hope that it will be useful,
+;; the Free Software Foundation; either version 2, or (at your option)
+;; any later version.
+
+;; GNU Emacs is distributed in the hope that it will be useful,
 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 ;; GNU General Public License for more details.
-;; 
-;; You should have received a copy of the GNU General Public License
-;; along with this program; if not, write to the Free Software
-;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
-;; LCD Archive Entry:
-;; elp|Barry A. Warsaw|tools-help@anthem.nlm.nih.gov|
-;; Emacs Lisp Profiler|
-;; 1994/06/06 22:38:07|2.11|~/misc/elp.el.Z|
+;; You should have received a copy of the GNU General Public License
+;; along with GNU Emacs; see the file COPYING.  If not, write to the
+;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
 
 ;;; Commentary:
 ;;
-;; This program is based on the only two existing Emacs Lisp profilers
-;; that I'm aware of, Boaz Ben-Zvi's profile.el, and Root Boy Jim's
-;; profiler.el. Both were written for Emacs 18 and both were pretty
-;; good first shots at profiling, but I found that they didn't provide
-;; the functionality or interface that I wanted.  So I wrote this.
-;; I've tested elp in Lucid Emacs 19.9 and in Emacs 19.22. There's no
-;; point in even trying to make this work with Emacs 18.
-
-;; Unlike previous profilers, elp uses Emacs 19's built-in function
-;; current-time to return interval times.  This obviates the need for
-;; both an external C program and Emacs processes to communicate with
-;; such a program, and thus simplifies the package as a whole.  One
-;; small shortcut: I throw away the most significant 16 bits of
-;; seconds returned by current-time since I doubt anyone will ever
-;; want to profile stuff on the order of 18 hours.  2^16 == 65536
-;; seconds == ~1092 minutes == ~18 hours.
-
-;; Note that there are plenty of factors that could make the times
-;; reported unreliable, including the accuracy and granularity of your
-;; system clock, and the overhead spent in lisp calculating and
-;; recording the intervals.  The latter I figure is pretty constant
-;; so, while the times may not be entirely accurate, I think they'll
-;; give you a good feel for the relative amount of work spent in the
-;; various lisp routines you are profiling.  Note further that times
-;; are calculated using wall-clock time, so other system load will
-;; affect accuracy too.
-
-;; There are only 3 variables you can change to customize behavior of
-;; elp. See below for their description.
-;;
-;; Here is a list of the interactive commands you can use:
-;;   elp-instrument-function
-;;   elp-restore-function
-;;   elp-instrument-list
-;;   elp-restore-list
-;;   elp-restore-all
-;;   elp-reset-function
-;;   elp-reset-list
-;;   elp-reset-all
-;;   elp-results
-;;   elp-submit-bug-report
-;;
-;; Here are some brief usage notes.  If you want to profile a bunch of
-;; functions, set elp-function-list to the list of symbols, then call
-;; elp-instrument-list.  This hacks the functions so that profiling
-;; information is recorded whenever they are called.  To print out the
-;; current results, use elp-results.  With elp-reset-after-results set
-;; to non-nil, profiling information will be reset whenever the
-;; results are displayed, but you can reset all profiling info with
+;; If you want to profile a bunch of functions, set elp-function-list
+;; to the list of symbols, then do a M-x elp-instrument-list.  This
+;; hacks those functions so that profiling information is recorded
+;; whenever they are called.  To print out the current results, use
+;; M-x elp-results.  If you want output to go to standard-output
+;; instead of a separate buffer, setq elp-use-standard-output to
+;; non-nil.  With elp-reset-after-results set to non-nil, profiling
+;; information will be reset whenever the results are displayed.  You
+;; can also reset all profiling info at any time with M-x
 ;; elp-reset-all.
 ;;
+;; You can also instrument all functions in a package, provided that
+;; the package follows the GNU coding standard of a common textural
+;; prefix.  Use M-x elp-instrument-package for this.
+;;
 ;; If you want to sort the results, set elp-sort-by-function to some
 ;; predicate function.  The three most obvious choices are predefined:
 ;; elp-sort-by-call-count, elp-sort-by-average-time, and
-;; elp-sort-by-total-time.
+;; elp-sort-by-total-time.  Also, you can prune from the output, all
+;; functions that have been called fewer than a given number of times
+;; by setting elp-report-limit.
 ;;
 ;; Elp can instrument byte-compiled functions just as easily as
-;; interpreted functions.  However, when you redefine a function (e.g.
-;; with eval-defun), you'll need to re-instrument it with
-;; elp-instrument-function.  Re-instrumenting resets profiling
-;; information for that function.  Elp can also handle interactive
-;; functions (i.e. commands), but of course any time spent idling for
-;; user prompts will show up in the timing results.
+;; interpreted functions, but it cannot instrument macros.  However,
+;; when you redefine a function (e.g. with eval-defun), you'll need to
+;; re-instrument it with M-x elp-instrument-function.  This will also
+;; reset profiling information for that function.  Elp can handle
+;; interactive functions (i.e. commands), but of course any time spent
+;; idling for user prompts will show up in the timing results.
 ;;
 ;; You can also designate a `master' function.  Profiling times will
 ;; be gathered for instrumented functions only during execution of
 ;;  (defun baz () (bar) (foo))
 ;;
 ;; and you want to find out the amount of time spent in bar and foo,
-;; but only during execution of bar, make bar the master and the call
-;; of foo from baz will not add to foo's total timing sums.  Use
-;; elp-set-master and elp-unset-master to utilize this feature.  Only
-;; one master function can be used at a time.
+;; but only during execution of bar, make bar the master.  The call of
+;; foo from baz will not add to foo's total timing sums.  Use M-x
+;; elp-set-master and M-x elp-unset-master to utilize this feature.
+;; Only one master function can be set at a time.
 
 ;; You can restore any function's original function definition with
 ;; elp-restore-function.  The other instrument, restore, and reset
 ;; functions are provided for symmetry.
 
+;; Here is a list of variable you can use to customize elp:
+;;   elp-function-list
+;;   elp-reset-after-results
+;;   elp-sort-by-function
+;;   elp-report-limit
+;;
+;; Here is a list of the interactive commands you can use:
+;;   elp-instrument-function
+;;   elp-restore-function
+;;   elp-instrument-list
+;;   elp-restore-list
+;;   elp-instrument-package
+;;   elp-restore-all
+;;   elp-reset-function
+;;   elp-reset-list
+;;   elp-reset-all
+;;   elp-set-master
+;;   elp-unset-master
+;;   elp-results
+;;   elp-submit-bug-report
+
+;; Note that there are plenty of factors that could make the times
+;; reported unreliable, including the accuracy and granularity of your
+;; system clock, and the overhead spent in lisp calculating and
+;; recording the intervals.  I figure the latter is pretty constant,
+;; so while the times may not be entirely accurate, I think they'll
+;; give you a good feel for the relative amount of work spent in the
+;; various lisp routines you are profiling.  Note further that times
+;; are calculated using wall-clock time, so other system load will
+;; affect accuracy too.
+
+;;; Background:
+
+;; This program was inspired by the only two existing Emacs Lisp
+;; profilers that I'm aware of, Boaz Ben-Zvi's profile.el, and Root
+;; Boy Jim's profiler.el. Both were written for Emacs 18 and both were
+;; pretty good first shots at profiling, but I found that they didn't
+;; provide the functionality or interface that I wanted, so I wrote
+;; this.  I've tested elp in XEmacs 19 and Emacs 19.  There's no point
+;; in even trying to make this work with Emacs 18.
+
+;; Unlike previous profilers, elp uses Emacs 19's built-in function
+;; current-time to return interval times.  This obviates the need for
+;; both an external C program and Emacs processes to communicate with
+;; such a program, and thus simplifies the package as a whole.
+
+;; TBD:
+;; Make this act like a real profiler, so that it records time spent
+;; in all branches of execution.
+
 ;;; Code:
 
 \f
-;; start user configuration variables
+;; start of user configuration variables
 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
 
-(defvar elp-function-list nil
-  "*List of function to profile.")
+(defgroup elp nil
+  "Emacs Lisp Profiler"
+  :group 'lisp)
 
-(defvar elp-reset-after-results t
+(defcustom elp-function-list nil
+  "*List of functions to profile.
+Used by the command `elp-instrument-list'."
+  :type '(repeat function)
+  :group 'elp)
+
+(defcustom elp-reset-after-results t
   "*Non-nil means reset all profiling info after results are displayed.
-Results are displayed with the `elp-results' command.")
+Results are displayed with the `elp-results' command."
+  :type 'boolean
+  :group 'elp)
 
-(defvar elp-sort-by-function nil
+(defcustom elp-sort-by-function 'elp-sort-by-total-time
   "*Non-nil specifies elp results sorting function.
 These functions are currently available:
 
@@ -140,17 +160,40 @@ interface specified by the PRED argument for the `sort' defun.  Each
 \"element of LIST\" is really a 4 element vector where element 0 is
 the call count, element 1 is the total time spent in the function,
 element 2 is the average time spent in the function, and element 3 is
-the symbol's name string.")
+the symbol's name string."
+  :type 'function
+  :group 'elp)
+
+(defcustom elp-report-limit 1
+  "*Prevents some functions from being displayed in the results buffer.
+If a number, no function that has been called fewer than that number
+of times will be displayed in the output buffer.  If nil, all
+functions will be displayed."
+  :type '(choice integer
+                (const :tag "Show All" nil))
+  :group 'elp)
+
+(defcustom elp-use-standard-output nil
+  "*Non-nil says to output to `standard-output' instead of a buffer."
+  :type 'boolean
+  :group 'elp)
+
+(defcustom elp-recycle-buffers-p t
+  "*Nil says to not recycle the `elp-results-buffer'.
+In other words, a new unique buffer is create every time you run
+\\[elp-results]."
+  :type 'boolean
+  :group 'elp)
 
 
 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-;; end user configuration variables
+;; end of user configuration variables
 
 \f
-(defconst elp-version "2.11"
+(defconst elp-version "3.2"
   "ELP version number.")
 
-(defconst elp-help-address "tools-help@anthem.nlm.nih.gov"
+(defconst elp-help-address "tools-help@python.org"
   "Address accepting submissions of bug reports and questions.")
 
 (defvar elp-results-buffer "*ELP Profiling Results*"
@@ -170,14 +213,35 @@ This variable is set by the master function.")
   "Master function symbol.")
 
 \f
+;;;###autoload
 (defun elp-instrument-function (funsym)
   "Instrument FUNSYM for profiling.
 FUNSYM must be a symbol of a defined function."
   (interactive "aFunction to instrument: ")
-  ;; TBD what should we do if the function is already instrumented???
+  ;; restore the function.  this is necessary to avoid infinite
+  ;; recursion of already instrumented functions (i.e. elp-wrapper
+  ;; calling elp-wrapper ad infinitum).  it is better to simply
+  ;; restore the function than to throw an error.  this will work
+  ;; properly in the face of eval-defun because if the function was
+  ;; redefined, only the timer info will be nil'd out since
+  ;; elp-restore-function is smart enough not to trash the new
+  ;; definition.
+  (elp-restore-function funsym)
   (let* ((funguts (symbol-function funsym))
         (infovec (vector 0 0 funguts))
         (newguts '(lambda (&rest args))))
+    ;; we cannot profile macros
+    (and (eq (car-safe funguts) 'macro)
+        (error "ELP cannot profile macro: %s" funsym))
+    ;; TBD: at some point it might be better to load the autoloaded
+    ;; function instead of throwing an error.  if we do this, then we
+    ;; probably want elp-instrument-package to be updated with the
+    ;; newly loaded list of functions.  i'm not sure it's smart to do
+    ;; the autoload here, since that could have side effects, and
+    ;; elp-instrument-function is similar (in my mind) to defun-ish
+    ;; type functionality (i.e. it shouldn't execute the function).
+    (and (eq (car-safe funguts) 'autoload)
+        (error "ELP cannot profile autoloaded function: %s" funsym))
     ;; put rest of newguts together
     (if (commandp funsym)
        (setq newguts (append newguts '((interactive)))))
@@ -220,6 +284,7 @@ FUNSYM must be a symbol of a defined function."
              (cons funsym elp-all-instrumented-list)))
     ))
 
+;;;###autoload
 (defun elp-restore-function (funsym)
   "Restore an instrumented function to its original definition.
 Argument FUNSYM is the symbol of a defined function."
@@ -242,13 +307,17 @@ Argument FUNSYM is the symbol of a defined function."
     ;; because its possible the function got un-instrumented due to
     ;; circumstances beyond our control.  Also, check to make sure
     ;; that the current function symbol points to elp-wrapper.  If
-    ;; not, then the user probably did an eval-defun while the
-    ;; function was instrumented and we don't want to destroy the new
-    ;; definition.
+    ;; not, then the user probably did an eval-defun, or loaded a
+    ;; byte-compiled version, while the function was instrumented and
+    ;; we don't want to destroy the new definition.  can it ever be
+    ;; the case that a lisp function can be compiled instrumented?
     (and info
+        (functionp funsym)
+        (not (compiled-function-p (symbol-function funsym)))
         (assq 'elp-wrapper (symbol-function funsym))
         (fset funsym (aref info 2)))))
 
+;;;###autoload
 (defun elp-instrument-list (&optional list)
   "Instrument for profiling, all functions in `elp-function-list'.
 Use optional LIST if provided instead."
@@ -256,6 +325,25 @@ Use optional LIST if provided instead."
   (let ((list (or list elp-function-list)))
     (mapcar 'elp-instrument-function list)))
 
+;;;###autoload
+(defun elp-instrument-package (prefix)
+  "Instrument for profiling, all functions which start with PREFIX.
+For example, to instrument all ELP functions, do the following:
+
+    \\[elp-instrument-package] RET elp- RET"
+  (interactive "sPrefix of package to instrument: ")
+  (elp-instrument-list
+   (mapcar
+    'intern
+    (all-completions
+     prefix obarray
+     (function
+      (lambda (sym)
+       (and (fboundp sym)
+            (not (memq (car-safe (symbol-function sym)) '(autoload macro))))
+       ))
+     ))))
+
 (defun elp-restore-list (&optional list)
   "Restore the original definitions for all functions in `elp-function-list'.
 Use optional LIST if provided instead."
@@ -305,17 +393,16 @@ Use optional LIST if provided instead."
 
 (defun elp-unset-master ()
   "Unsets the master function."
+  (interactive)
   ;; when there's no master function, recording is turned on by default.
   (setq elp-master nil
        elp-record-p t))
 
 \f
-(defsubst elp-get-time ()
-  ;; get current time in seconds and microseconds. I throw away the
-  ;; most significant 16 bits of seconds since I doubt we'll ever want
-  ;; to profile lisp on the order of 18 hours. See notes at top of file.
-  (let ((now (current-time)))
-    (+ (float (nth 1 now)) (/ (float (nth 2 now)) 1000000.0))))
+(defsubst elp-elapsed-time (start end)
+  (+ (* (- (car end) (car start)) 65536.0)
+     (- (car (cdr end)) (car (cdr start)))
+     (/ (- (car (cdr (cdr end))) (car (cdr (cdr start)))) 1000000.0)))
 
 (defun elp-wrapper (funsym interactive-p args)
   "This function has been instrumented for profiling by the ELP.
@@ -339,18 +426,21 @@ original definition, use \\[elp-restore-function] or \\[elp-restore-all]."
                  (call-interactively func)
                (apply func args)))
       ;; we are recording times
-      (let ((enter-time (elp-get-time)))
+      (let (enter-time exit-time)
        ;; increment the call-counter
        (aset info 0 (1+ (aref info 0)))
        ;; now call the old symbol function, checking to see if it
        ;; should be called interactively.  make sure we return the
        ;; correct value
-       (setq result
-             (if interactive-p
-                 (call-interactively func)
-               (apply func args)))
+       (if interactive-p
+           (setq enter-time (current-time)
+                 result (call-interactively func)
+                 exit-time (current-time))
+         (setq enter-time (current-time)
+               result (apply func args)
+               exit-time (current-time)))
        ;; calculate total time in function
-       (aset info 1 (+ (aref info 1) (- (elp-get-time) enter-time)))
+       (aset info 1 (+ (aref info 1) (elp-elapsed-time enter-time exit-time)))
        ))
     ;; turn off recording if this is the master function
     (if (and elp-master
@@ -377,6 +467,21 @@ original definition, use \\[elp-restore-function] or \\[elp-restore-all]."
   ;; sort by highest average time spent in function. See `sort'.
   (>= (aref vec1 2) (aref vec2 2)))
 
+(defsubst elp-pack-number (number width)
+  ;; pack the NUMBER string into WIDTH characters, watching out for
+  ;; very small or large numbers
+  (if (<= (length number) width)
+      number
+    ;; check for very large or small numbers
+    (if (string-match "^\\(.*\\)\\(e[+-].*\\)$" number)
+       (concat (substring
+                (substring number (match-beginning 1) (match-end 1))
+                0
+                (- width (match-end 2) (- (match-beginning 2)) 3))
+               "..."
+               (substring number (match-beginning 2) (match-end 2)))
+      (concat (substring number 0 width)))))
+
 (defun elp-output-result (resultvec)
   ;; output the RESULTVEC into the results buffer. RESULTVEC is a 4 or
   ;; more element vector where aref 0 is the call count, aref 1 is the
@@ -388,23 +493,27 @@ original definition, use \\[elp-restore-function] or \\[elp-restore-all]."
         (at (aref resultvec 2))
         (symname (aref resultvec 3))
         callcnt totaltime avetime)
-    (insert symname)
-    (insert-char 32 (+ elp-field-len (- (length symname)) 2))
     (setq callcnt (number-to-string cc)
          totaltime (number-to-string tt)
          avetime (number-to-string at))
-    ;; print stuff out, formatting it nicely
-    (insert callcnt)
-    (insert-char 32 (+ elp-cc-len (- (length callcnt)) 2))
-    (if (> (length totaltime) elp-et-len)
-       (insert (substring totaltime 0 elp-et-len) "  ")
-      (insert totaltime)
-      (insert-char 32 (+ elp-et-len (- (length totaltime)) 2)))
-    (if (> (length avetime) elp-at-len)
-       (insert (substring avetime 0 elp-at-len))
-      (insert avetime))
-    (insert "\n")))
-
+    ;; possibly prune the results
+    (if (and elp-report-limit
+            (numberp elp-report-limit)
+            (< cc elp-report-limit))
+       nil
+      (insert symname)
+      (insert-char 32 (+ elp-field-len (- (length symname)) 2))
+      ;; print stuff out, formatting it nicely
+      (insert callcnt)
+      (insert-char 32 (+ elp-cc-len (- (length callcnt)) 2))
+      (let ((ttstr (elp-pack-number totaltime elp-et-len))
+           (atstr (elp-pack-number avetime elp-at-len)))
+       (insert ttstr)
+       (insert-char 32 (+ elp-et-len (- (length ttstr)) 2))
+       (insert atstr))
+      (insert "\n"))))
+
+;;;###autoload
 (defun elp-results ()
   "Display current profiling results.
 If `elp-reset-after-results' is non-nil, then current profiling
@@ -412,7 +521,9 @@ information for all instrumented functions are reset after results are
 displayed."
   (interactive)
   (let ((curbuf (current-buffer))
-       (resultsbuf (get-buffer-create elp-results-buffer)))
+       (resultsbuf (if elp-recycle-buffers-p
+                       (get-buffer-create elp-results-buffer)
+                     (generate-new-buffer elp-results-buffer))))
     (set-buffer resultsbuf)
     (erase-buffer)
     (beginning-of-buffer)
@@ -468,6 +579,9 @@ displayed."
     ;; now pop up results buffer
     (set-buffer curbuf)
     (pop-to-buffer resultsbuf)
+    ;; copy results to standard-output?
+    (if (or elp-use-standard-output noninteractive)
+       (princ (buffer-substring (point-min) (point-max))))
     ;; reset profiling info if desired
     (and elp-reset-after-results
         (elp-reset-all))))
@@ -476,6 +590,7 @@ displayed."
 (eval-when-compile
  (require 'reporter))
 
+;;;###autoload
 (defun elp-submit-bug-report ()
   "Submit via mail, a bug report on elp."
   (interactive)
@@ -484,10 +599,10 @@ displayed."
    (require 'reporter)
    (reporter-submit-bug-report
     elp-help-address (concat "elp " elp-version)
-    '(elp-reset-after-results
+    '(elp-report-limit
+      elp-reset-after-results
       elp-sort-by-function))))
-
 \f
 (provide 'elp)
-;; elp.el ends here
 
+;; elp.el ends here