0.pre7.38:
[sbcl.git] / src / code / profile.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3 ;;;;
4 ;;;; This software is derived from the CMU CL system, which was
5 ;;;; written at Carnegie Mellon University and released into the
6 ;;;; public domain. The software is in the public domain and is
7 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
8 ;;;; files for more information.
9
10 (in-package "SB-PROFILE") ; (SB-, not SB!, since we're built in warm load.)
11 \f
12 ;;;; reading internal run time with high resolution and low overhead
13
14 ;;; FIXME: It might make sense to replace this with something
15 ;;; with finer resolution, e.g. milliseconds or microseconds.
16 ;;; For that matter, maybe we should boost the internal clock
17 ;;; up to something faster, like milliseconds.
18
19 (defconstant +ticks-per-second+ internal-time-units-per-second)
20
21 (declaim (inline get-internal-ticks))
22 (defun get-internal-ticks () (get-internal-run-time))
23 \f
24 ;;;; implementation-dependent interfaces
25
26 #|
27 ;;; To avoid unnecessary consing in the "encapsulation" code, we want
28 ;;; find out the number of required arguments, and use &REST to
29 ;;; capture only non-required arguments. This function returns (VALUES
30 ;;; MIN-ARGS OPTIONALS-P), where MIN-ARGS is the number of required
31 ;;; arguments and OPTIONALS-P is true iff there are any non-required
32 ;;; arguments (such as &OPTIONAL, &REST, or &KEY).
33 (declaim (ftype (function ((or symbol cons)) (values fixnum t)) fun-signature))
34 (defun fun-signature (name)
35   (let ((type (info :function :type name)))
36     (cond ((not (function-type-p type))
37            (values 0 t))
38           (t
39            (values (length (function-type-required type))
40                    (or (function-type-optional type)
41                        (function-type-keyp type)
42                        (function-type-rest type)))))))
43 |#
44 \f
45 ;;;; global data structures
46
47 ;;; We associate a PROFILE-INFO structure with each profiled function
48 ;;; name. This holds the functions that we call to manipulate the
49 ;;; closure which implements the encapsulation.
50 (defvar *profiled-function-name->info* (make-hash-table))
51 (defstruct (profile-info (:copier nil))
52   (name              (required-argument) :read-only t)
53   (encapsulated-fun  (required-argument) :type function :read-only t)
54   (encapsulation-fun (required-argument) :type function :read-only t)
55   (read-stats-fun    (required-argument) :type function :read-only t)
56   (clear-stats-fun   (required-argument) :type function :read-only t))
57
58 ;;; These variables are used to subtract out the time and consing for
59 ;;; recursive and other dynamically nested profiled calls. The total
60 ;;; resource consumed for each nested call is added into the
61 ;;; appropriate variable. When the outer function returns, these
62 ;;; amounts are subtracted from the total.
63 (defvar *enclosed-ticks* 0)
64 (defvar *enclosed-consing* 0)
65 (declaim (type (or pcounter fixnum) *enclosed-ticks* *enclosed-consing*))
66
67 ;;; This variable is also used to subtract out time for nested
68 ;;; profiled calls. The time inside the profile wrapper call --
69 ;;; between its two calls to GET-INTERNAL-TICKS -- is accounted
70 ;;; for by the *ENCLOSED-TIME* variable. However, there's also extra
71 ;;; overhead involved, before we get to the first call to
72 ;;; GET-INTERNAL-TICKS, and after we get to the second call. By
73 ;;; keeping track of the count of enclosed profiled calls, we can try
74 ;;; to compensate for that.
75 (defvar *enclosed-profiles* 0)
76 (declaim (type (or pcounter fixnum) *enclosed-profiles*))
77
78 ;;; the encapsulated function we're currently computing profiling data
79 ;;; for, recorded so that we can detect the problem of
80 ;;; PROFILE-computing machinery calling a function which has itself
81 ;;; been PROFILEd
82 (defvar *computing-profiling-data-for*)
83
84 ;;; the components of profiling overhead
85 (defstruct (overhead (:copier nil))
86   ;; the number of ticks a bare function call takes. This is
87   ;; factored into the other overheads, but not used for itself.
88   (call (required-argument) :type single-float :read-only t)
89   ;; the number of ticks that will be charged to a profiled
90   ;; function due to the profiling code
91   (internal (required-argument) :type single-float :read-only t)
92   ;; the number of ticks of overhead for profiling that a single
93   ;; profiled call adds to the total runtime for the program
94   (total (required-argument) :type single-float :read-only t))
95 (defvar *overhead*)
96 (declaim (type overhead *overhead*))
97 (makunbound '*overhead*) ; in case we reload this file when tweaking
98 \f
99 ;;;; profile encapsulations
100
101 ;;; Trade off space for time by handling the usual all-FIXNUM cases
102 ;;; inline.
103 (defmacro fastbig- (x y)
104   (once-only ((x x) (y y))
105     `(if (and (typep ,x '(and fixnum unsigned-byte))
106               (typep ,y '(and fixnum unsigned-byte)))
107          ;; special case: can use fixnum arithmetic and be guaranteed
108          ;; the result is also a fixnum
109          (- ,x ,y)
110          ;; general case
111          (- ,x ,y))))
112 (defmacro fastbig-1+ (x)
113   (once-only ((x x))
114     `(if (typep ,x 'index)
115          (1+ ,x)
116          (1+ ,x))))
117
118 ;;; Return a collection of closures over the same lexical context,
119 ;;;   (VALUES ENCAPSULATION-FUN READ-STATS-FUN CLEAR-STATS-FUN).
120 ;;;
121 ;;; ENCAPSULATION-FUN is a plug-in replacement for ENCAPSULATED-FUN,
122 ;;; which updates statistics whenver it's called.
123 ;;;
124 ;;; READ-STATS-FUN returns the statistics:
125 ;;;   (VALUES COUNT TIME CONSING PROFILE).
126 ;;; COUNT is the count of calls to ENCAPSULATION-FUN. TICKS is
127 ;;; the total number of ticks spent in ENCAPSULATED-FUN.
128 ;;; CONSING is the total consing of ENCAPSULATION-FUN. PROFILE is the
129 ;;; number of calls to the profiled function, stored for the purposes
130 ;;; of trying to estimate that part of profiling overhead which occurs
131 ;;; outside the interval between the profile wrapper function's timer
132 ;;; calls.
133 ;;;
134 ;;; CLEAR-STATS-FUN clears the statistics.
135 ;;;
136 ;;; (The reason for implementing this as coupled closures, with the
137 ;;; counts built into the lexical environment, is that we hope this
138 ;;; will minimize profiling overhead.)
139 (defun profile-encapsulation-lambdas (encapsulated-fun)
140   (declare (type function encapsulated-fun))
141   (let* ((count 0)
142          (ticks 0)
143          (consing 0)
144          (profiles 0))
145     (declare (type (or pcounter fixnum) count ticks consing profiles))
146     (values
147      ;; ENCAPSULATION-FUN
148      (lambda (&more arg-context arg-count)
149        (declare (optimize speed safety))
150        ;; Make sure that we're not recursing infinitely.
151        (when (boundp '*computing-profiling-data-for*)
152          (unprofile-all) ; to avoid further recursion
153          (error "~@<When computing profiling data for ~S, the profiled function ~S was called. To get out of this infinite recursion, all functions have been unprofiled. (Since the profiling system evidently uses ~S in its computations, it looks as though it's a bad idea to profile it.)~:@>"
154                 *computing-profiling-data-for*
155                 encapsulated-fun
156                 encapsulated-fun))
157        ;; FIXME: Probably when this is stable, we should optimize (SAFETY 0).
158        (fastbig-incf-pcounter-or-fixnum count 1)
159        (let ((dticks 0)
160              (dconsing 0)
161              (inner-enclosed-profiles 0))
162          (declare (type unsigned-byte dticks dconsing))
163          (declare (type unsigned-byte inner-enclosed-profiles))
164          (aver (typep dticks 'unsigned-byte))
165          (aver (typep dconsing 'unsigned-byte))
166          (aver (typep inner-enclosed-profiles 'unsigned-byte))
167          (multiple-value-prog1
168              (let* ((start-ticks (get-internal-ticks))
169                     (*enclosed-ticks* 0)
170                     (*enclosed-consing* 0)
171                     (*enclosed-profiles* 0)
172                     (nbf0 *n-bytes-freed-or-purified*)
173                     (dynamic-usage-0 (sb-kernel:dynamic-usage)))
174                (declare (inline pcounter-or-fixnum->integer))
175                (multiple-value-prog1
176                    (multiple-value-call encapsulated-fun
177                                         (sb-c:%more-arg-values arg-context
178                                                                0
179                                                                arg-count))
180                  (let ((*computing-profiling-data-for* encapsulated-fun)
181                        (dynamic-usage-1 (sb-kernel:dynamic-usage)))
182                    (setf dticks (fastbig- (get-internal-ticks) start-ticks))
183                    (setf dconsing
184                          (if (eql *n-bytes-freed-or-purified* nbf0)
185                              ;; common special case where we can avoid
186                              ;; bignum arithmetic
187                              (- dynamic-usage-1 dynamic-usage-0)
188                              ;; general case
189                              (- (get-bytes-consed) nbf0 dynamic-usage-0)))
190                    (setf inner-enclosed-profiles
191                          (pcounter-or-fixnum->integer *enclosed-profiles*))
192                    (let ((net-dticks (fastbig- dticks *enclosed-ticks*)))
193                      (fastbig-incf-pcounter-or-fixnum ticks net-dticks))
194                    (let ((net-dconsing (fastbig- dconsing *enclosed-consing*)))
195                      (fastbig-incf-pcounter-or-fixnum consing net-dconsing))
196                    (fastbig-incf-pcounter-or-fixnum profiles
197                                                     inner-enclosed-profiles))))
198            (fastbig-incf-pcounter-or-fixnum *enclosed-ticks* dticks)
199            (fastbig-incf-pcounter-or-fixnum *enclosed-consing* dconsing)
200            (fastbig-incf-pcounter-or-fixnum *enclosed-profiles*
201                                             (fastbig-1+
202                                              inner-enclosed-profiles)))))
203      ;; READ-STATS-FUN
204      (lambda ()
205        (values (pcounter-or-fixnum->integer count)
206                (pcounter-or-fixnum->integer ticks)
207                (pcounter-or-fixnum->integer consing)
208                (pcounter-or-fixnum->integer profiles)))
209      ;; CLEAR-STATS-FUN
210      (lambda ()
211        (setf count 0
212              ticks 0
213              consing 0
214              profiles 0)))))
215 \f
216 ;;;; interfaces
217
218 ;;; A symbol or (SETF FOO) list names a function, a string names all
219 ;;; the functions named by symbols in the named package.
220 (defun mapc-on-named-functions (function names)
221   (dolist (name names)
222     (etypecase name
223       (symbol (funcall function name))
224       (list
225        ;; We call this just for the side effect of checking that
226        ;; NAME is a legal function name:
227        (function-name-block-name name)
228        ;; Then we map onto it.
229        (funcall function name))
230       (string (let ((package (find-undeleted-package-or-lose name)))
231                 (do-symbols (symbol package)
232                   (when (eq (symbol-package symbol) package)
233                     (when (fboundp symbol)
234                       (funcall function symbol))
235                     (let ((setf-name `(setf ,symbol)))
236                       (when (fboundp setf-name)
237                         (funcall function setf-name)))))))))
238   (values))
239
240 ;;; Profile the named function, which should exist and not be profiled
241 ;;; already.
242 (defun profile-1-unprofiled-function (name)
243   (declare #.*optimize-byte-compilation*)
244   (let ((encapsulated-fun (fdefinition name)))
245     (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
246         (profile-encapsulation-lambdas encapsulated-fun)
247       (setf (fdefinition name)
248             encapsulation-fun)
249       (setf (gethash name *profiled-function-name->info*)
250             (make-profile-info :name name
251                                :encapsulated-fun encapsulated-fun
252                                :encapsulation-fun encapsulation-fun
253                                :read-stats-fun read-stats-fun
254                                :clear-stats-fun clear-stats-fun))
255       (values))))
256
257 ;;; Profile the named function. If already profiled, unprofile first.
258 (defun profile-1-function (name)
259   (declare #.*optimize-byte-compilation*)
260   (cond ((fboundp name)
261          (when (gethash name *profiled-function-name->info*)
262            (warn "~S is already profiled, so unprofiling it first." name)
263            (unprofile-1-function name))
264          (profile-1-unprofiled-function name))
265         (t
266          (warn "ignoring undefined function ~S" name)))
267   (values))
268
269 ;;; Unprofile the named function, if it is profiled.
270 (defun unprofile-1-function (name)
271   (declare #.*optimize-byte-compilation*)
272   (let ((pinfo (gethash name *profiled-function-name->info*)))
273     (cond (pinfo
274            (remhash name *profiled-function-name->info*)
275            (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
276                (setf (fdefinition name) (profile-info-encapsulated-fun pinfo))
277                (warn "preserving current definition of redefined function ~S"
278                      name)))
279           (t
280            (warn "~S is not a profiled function." name))))
281   (values))
282
283 (defmacro profile (&rest names)
284   #+sb-doc
285   "PROFILE Name*
286
287    If no names are supplied, return the list of profiled functions.
288
289    If names are supplied, wrap profiling code around the named functions.
290    As in TRACE, the names are not evaluated. A symbol names a function.
291    A string names all the functions named by symbols in the named
292    package. If a function is already profiled, then unprofile and
293    reprofile (useful to notice function redefinition.)  If a name is
294    undefined, then we give a warning and ignore it. See also
295    UNPROFILE, REPORT and RESET."
296   (declare #.*optimize-byte-compilation*)
297   (if (null names)
298       `(loop for k being each hash-key in *profiled-function-name->info*
299              collecting k)
300       `(mapc-on-named-functions #'profile-1-function ',names)))
301
302 (defmacro unprofile (&rest names)
303   #+sb-doc
304   "Unwrap any profiling code around the named functions, or if no names
305   are given, unprofile all profiled functions. A symbol names
306   a function. A string names all the functions named by symbols in the
307   named package. NAMES defaults to the list of names of all currently 
308   profiled functions."
309   (declare #.*optimize-byte-compilation*)
310   (if names
311       `(mapc-on-named-functions #'unprofile-1-function ',names)
312       `(unprofile-all)))
313
314 (defun unprofile-all ()
315   (declare #.*optimize-byte-compilation*)
316   (dohash (name profile-info *profiled-function-name->info*)
317     (declare (ignore profile-info))
318     (unprofile-1-function name)))
319
320 (defun reset ()
321   "Reset the counters for all profiled functions."
322   (dohash (name profile-info *profiled-function-name->info*)
323     (declare (ignore name))
324     (funcall (profile-info-clear-stats-fun profile-info))))
325 \f
326 ;;;; reporting results
327
328 (defstruct (time-info (:copier nil))
329   name
330   calls
331   seconds
332   consing)
333
334 ;;; Return our best guess for the run time in a function, subtracting
335 ;;; out factors for profiling overhead. We subtract out the internal
336 ;;; overhead for each call to this function, since the internal
337 ;;; overhead is the part of the profiling overhead for a function that
338 ;;; is charged to that function.
339 ;;;
340 ;;; We also subtract out a factor for each call to a profiled function
341 ;;; within this profiled function. This factor is the total profiling
342 ;;; overhead *minus the internal overhead*. We don't subtract out the
343 ;;; internal overhead, since it was already subtracted when the nested
344 ;;; profiled functions subtracted their running time from the time for
345 ;;; the enclosing function.
346 (defun compensate-time (calls ticks profile)
347   (let ((raw-compensated
348          (- (/ (float ticks) (float +ticks-per-second+))
349             (* (overhead-internal *overhead*) (float calls))
350             (* (- (overhead-total *overhead*)
351                   (overhead-internal *overhead*))
352                (float profile)))))
353     (max raw-compensated 0.0)))
354
355 (defun report ()
356   "Report results from profiling. The results are approximately adjusted
357 for profiling overhead. The compensation may be rather inaccurate when
358 bignums are involved in runtime calculation, as in a very-long-running
359 Lisp process."
360   (declare #.*optimize-external-despite-byte-compilation*)
361   (unless (boundp '*overhead*)
362     (setf *overhead*
363           (compute-overhead)))
364   (let ((time-info-list ())
365         (no-call-name-list ()))
366     (dohash (name pinfo *profiled-function-name->info*)
367       (unless (eq (fdefinition name)
368                   (profile-info-encapsulation-fun pinfo))
369         (warn "Function ~S has been redefined, so times may be inaccurate.~@
370                PROFILE it again to record calls to the new definition."
371               name))
372       (multiple-value-bind (calls ticks consing profile)
373           (funcall (profile-info-read-stats-fun pinfo))
374         (if (zerop calls)
375             (push name no-call-name-list)
376             (push (make-time-info :name name
377                                   :calls calls
378                                   :seconds (compensate-time calls
379                                                             ticks
380                                                             profile)
381                                   :consing consing)
382                   time-info-list))))
383
384     (setf time-info-list
385           (sort time-info-list
386                 #'>=
387                 :key #'time-info-seconds))
388
389     (format *trace-output*
390             "~&  seconds  |  consed   |  calls  |  sec/call  |  name~@
391                ------------------------------------------------------~%")
392
393     (let ((total-time 0.0)
394           (total-consed 0)
395           (total-calls 0))
396       (dolist (time-info time-info-list)
397         (incf total-time (time-info-seconds time-info))
398         (incf total-calls (time-info-calls time-info))
399         (incf total-consed (time-info-consing time-info))
400         (format *trace-output*
401                 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
402                 (time-info-seconds time-info)
403                 (time-info-consing time-info)
404                 (time-info-calls time-info)
405                 (/ (time-info-seconds time-info)
406                    (float (time-info-calls time-info)))
407                 (time-info-name time-info)))
408       (format *trace-output*
409               "------------------------------------------------------~@
410               ~10,3F | ~9:D | ~7:D |        | Total~%"
411               total-time total-consed total-calls)
412       (format *trace-output*
413               "~%estimated total profiling overhead: ~4,2F seconds~%"
414               (* (overhead-total *overhead*) (float total-calls)))
415       (format *trace-output*
416               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
417               (overhead-call *overhead*)
418               (overhead-total *overhead*)
419               (overhead-internal *overhead*)))
420
421     (when no-call-name-list
422       (format *trace-output*
423               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
424               (sort no-call-name-list #'string<
425                     :key (lambda (name)
426                            (symbol-name (function-name-block-name name))))))
427
428     (values)))
429 \f
430 ;;;; overhead estimation
431
432 ;;; We average the timing overhead over this many iterations.
433 ;;;
434 ;;; (This is a variable, not a constant, so that it can be set in
435 ;;; .sbclrc if desired. Right now, that's an unsupported extension
436 ;;; that I (WHN) use for my own experimentation, but it might
437 ;;; become supported someday. Comments?)
438 (declaim (type unsigned-byte *timer-overhead-iterations*))
439 (defparameter *timer-overhead-iterations*
440   500000)
441
442 ;;; a dummy function that we profile to find profiling overhead
443 (declaim (notinline compute-overhead-aux))
444 (defun compute-overhead-aux (x)
445   (declare (ignore x)))
446
447 ;;; Return a newly computed OVERHEAD object.
448 (defun compute-overhead ()
449   (format *debug-io* "~&measuring PROFILE overhead..")
450   (flet ((frob ()
451            (let ((start (get-internal-ticks))
452                  (fun (symbol-function 'compute-overhead-aux)))
453              (dotimes (i *timer-overhead-iterations*)
454                (funcall fun fun))
455              (/ (float (- (get-internal-ticks) start))
456                 (float +ticks-per-second+)
457                 (float *timer-overhead-iterations*)))))
458     (let (;; Measure unprofiled calls to estimate call overhead.
459           (call-overhead (frob))
460           total-overhead
461           internal-overhead)
462       ;; Measure profiled calls to estimate profiling overhead.
463       (unwind-protect
464           (progn
465             (profile compute-overhead-aux)
466             (setf total-overhead
467                   (- (frob) call-overhead)))
468         (let* ((pinfo (gethash 'compute-overhead-aux
469                                *profiled-function-name->info*))
470                (read-stats-fun (profile-info-read-stats-fun pinfo))
471                (time (nth-value 1 (funcall read-stats-fun))))
472           (setf internal-overhead
473                 (/ (float time)
474                    (float +ticks-per-second+)
475                    (float *timer-overhead-iterations*))))
476         (unprofile compute-overhead-aux))
477       (prog1
478           (make-overhead :call call-overhead
479                          :total total-overhead
480                          :internal internal-overhead)
481         (format *debug-io* "done~%")))))
482
483 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
484 ;;; then load the old *OVERHEAD* value from the .core file into a
485 ;;; different machine running at a different speed. We avoid this by
486 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
487 (pushnew (lambda ()
488            (makunbound '*overhead*))
489          *before-save-initializations*)