0.6.12.49:
[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 (sb-c:&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                     (nbf-pcounter *n-bytes-freed-or-purified-pcounter*)
173                     ;; Typically NBF-PCOUNTER will represent a bignum.
174                     ;; In general we don't want to cons up a new
175                     ;; bignum for every encapsulated call, so instead
176                     ;; we keep track of the PCOUNTER internals, so
177                     ;; that as long as we only cons small amounts,
178                     ;; we'll almost always just do fixnum arithmetic.
179                     ;; (And for encapsulated functions which cons
180                     ;; large amounts, then a single extra consed
181                     ;; bignum tends to be proportionally negligible.)
182                     (nbf0-integer (pcounter-integer nbf-pcounter))
183                     (nbf0-fixnum (pcounter-fixnum nbf-pcounter))
184                     (dynamic-usage-0 (sb-kernel:dynamic-usage)))
185                (declare (inline pcounter-or-fixnum->integer))
186                (multiple-value-prog1
187                    (multiple-value-call encapsulated-fun
188                                         (sb-c:%more-arg-values arg-context
189                                                                0
190                                                                arg-count))
191                  (let ((*computing-profiling-data-for* encapsulated-fun)
192                        (dynamic-usage-1 (sb-kernel:dynamic-usage)))
193                    (setf dticks (fastbig- (get-internal-ticks) start-ticks))
194                    (setf dconsing
195                          (if (and (eq (pcounter-integer nbf-pcounter)
196                                       nbf0-integer)
197                                   (eq (pcounter-fixnum nbf-pcounter)
198                                       nbf0-fixnum))
199                              ;; common special case where we can avoid
200                              ;; bignum arithmetic
201                              (- dynamic-usage-1
202                                 dynamic-usage-0)
203                              ;; general case
204                              (- (get-bytes-consed)
205                                 nbf0-integer
206                                 nbf0-fixnum
207                                 dynamic-usage-0)))
208                    (setf inner-enclosed-profiles
209                          (pcounter-or-fixnum->integer *enclosed-profiles*))
210                    (let ((net-dticks (fastbig- dticks *enclosed-ticks*)))
211                      (fastbig-incf-pcounter-or-fixnum ticks net-dticks))
212                    (let ((net-dconsing (fastbig- dconsing *enclosed-consing*)))
213                      (fastbig-incf-pcounter-or-fixnum consing net-dconsing))
214                    (fastbig-incf-pcounter-or-fixnum profiles
215                                                     inner-enclosed-profiles))))
216            (fastbig-incf-pcounter-or-fixnum *enclosed-ticks* dticks)
217            (fastbig-incf-pcounter-or-fixnum *enclosed-consing* dconsing)
218            (fastbig-incf-pcounter-or-fixnum *enclosed-profiles*
219                                             (fastbig-1+
220                                              inner-enclosed-profiles)))))
221      ;; READ-STATS-FUN
222      (lambda ()
223        (values (pcounter-or-fixnum->integer count)
224                (pcounter-or-fixnum->integer ticks)
225                (pcounter-or-fixnum->integer consing)
226                (pcounter-or-fixnum->integer profiles)))
227      ;; CLEAR-STATS-FUN
228      (lambda ()
229        (setf count 0
230              ticks 0
231              consing 0
232              profiles 0)))))
233 \f
234 ;;;; interfaces
235
236 ;;; A symbol or (SETF FOO) list names a function, a string names all
237 ;;; the functions named by symbols in the named package.
238 (defun mapc-on-named-functions (function names)
239   (dolist (name names)
240     (etypecase name
241       (symbol (funcall function name))
242       (list
243        ;; We call this just for the side effect of checking that
244        ;; NAME is a legal function name:
245        (function-name-block-name name)
246        ;; Then we map onto it.
247        (funcall function name))
248       (string (let ((package (find-undeleted-package-or-lose name)))
249                 (do-symbols (symbol package)
250                   (when (eq (symbol-package symbol) package)
251                     (when (fboundp symbol)
252                       (funcall function symbol))
253                     (let ((setf-name `(setf ,symbol)))
254                       (when (fboundp setf-name)
255                         (funcall function setf-name)))))))))
256   (values))
257
258 ;;; Profile the named function, which should exist and not be profiled
259 ;;; already.
260 (defun profile-1-unprofiled-function (name)
261   (declare #.*optimize-byte-compilation*)
262   (let ((encapsulated-fun (fdefinition name)))
263     (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
264         (profile-encapsulation-lambdas encapsulated-fun)
265       (setf (fdefinition name)
266             encapsulation-fun)
267       (setf (gethash name *profiled-function-name->info*)
268             (make-profile-info :name name
269                                :encapsulated-fun encapsulated-fun
270                                :encapsulation-fun encapsulation-fun
271                                :read-stats-fun read-stats-fun
272                                :clear-stats-fun clear-stats-fun))
273       (values))))
274
275 ;;; Profile the named function. If already profiled, unprofile first.
276 (defun profile-1-function (name)
277   (declare #.*optimize-byte-compilation*)
278   (cond ((fboundp name)
279          (when (gethash name *profiled-function-name->info*)
280            (warn "~S is already profiled, so unprofiling it first." name)
281            (unprofile-1-function name))
282          (profile-1-unprofiled-function name))
283         (t
284          (warn "ignoring undefined function ~S" name)))
285   (values))
286
287 ;;; Unprofile the named function, if it is profiled.
288 (defun unprofile-1-function (name)
289   (declare #.*optimize-byte-compilation*)
290   (let ((pinfo (gethash name *profiled-function-name->info*)))
291     (cond (pinfo
292            (remhash name *profiled-function-name->info*)
293            (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
294                (setf (fdefinition name) (profile-info-encapsulated-fun pinfo))
295                (warn "preserving current definition of redefined function ~S"
296                      name)))
297           (t
298            (warn "~S is not a profiled function." name))))
299   (values))
300
301 (defmacro profile (&rest names)
302   #+sb-doc
303   "PROFILE Name*
304
305    If no names are supplied, return the list of profiled functions.
306
307    If names are supplied, wrap profiling code around the named functions.
308    As in TRACE, the names are not evaluated. A symbol names a function.
309    A string names all the functions named by symbols in the named
310    package. If a function is already profiled, then unprofile and
311    reprofile (useful to notice function redefinition.)  If a name is
312    undefined, then we give a warning and ignore it. See also
313    UNPROFILE, REPORT and RESET."
314   (declare #.*optimize-byte-compilation*)
315   (if (null names)
316       `(loop for k being each hash-key in *profiled-function-name->info*
317              collecting k)
318       `(mapc-on-named-functions #'profile-1-function ',names)))
319
320 (defmacro unprofile (&rest names)
321   #+sb-doc
322   "Unwrap any profiling code around the named functions, or if no names
323   are given, unprofile all profiled functions. A symbol names
324   a function. A string names all the functions named by symbols in the
325   named package. NAMES defaults to the list of names of all currently 
326   profiled functions."
327   (declare #.*optimize-byte-compilation*)
328   (if names
329       `(mapc-on-named-functions #'unprofile-1-function ',names)
330       `(unprofile-all)))
331
332 (defun unprofile-all ()
333   (declare #.*optimize-byte-compilation*)
334   (dohash (name profile-info *profiled-function-name->info*)
335     (declare (ignore profile-info))
336     (unprofile-1-function name)))
337
338 (defun reset ()
339   "Reset the counters for all profiled functions."
340   (dohash (name profile-info *profiled-function-name->info*)
341     (declare (ignore name))
342     (funcall (profile-info-clear-stats-fun profile-info))))
343 \f
344 ;;;; reporting results
345
346 (defstruct (time-info (:copier nil))
347   name
348   calls
349   seconds
350   consing)
351
352 ;;; Return our best guess for the run time in a function, subtracting
353 ;;; out factors for profiling overhead. We subtract out the internal
354 ;;; overhead for each call to this function, since the internal
355 ;;; overhead is the part of the profiling overhead for a function that
356 ;;; is charged to that function.
357 ;;;
358 ;;; We also subtract out a factor for each call to a profiled function
359 ;;; within this profiled function. This factor is the total profiling
360 ;;; overhead *minus the internal overhead*. We don't subtract out the
361 ;;; internal overhead, since it was already subtracted when the nested
362 ;;; profiled functions subtracted their running time from the time for
363 ;;; the enclosing function.
364 (defun compensate-time (calls ticks profile)
365   (let ((raw-compensated
366          (- (/ (float ticks) (float +ticks-per-second+))
367             (* (overhead-internal *overhead*) (float calls))
368             (* (- (overhead-total *overhead*)
369                   (overhead-internal *overhead*))
370                (float profile)))))
371     (max raw-compensated 0.0)))
372
373 (defun report ()
374   "Report results from profiling. The results are approximately adjusted
375 for profiling overhead. The compensation may be rather inaccurate when
376 bignums are involved in runtime calculation, as in a very-long-running
377 Lisp process."
378   (declare #.*optimize-external-despite-byte-compilation*)
379   (unless (boundp '*overhead*)
380     (setf *overhead*
381           (compute-overhead)))
382   (let ((time-info-list ())
383         (no-call-name-list ()))
384     (dohash (name pinfo *profiled-function-name->info*)
385       (unless (eq (fdefinition name)
386                   (profile-info-encapsulation-fun pinfo))
387         (warn "Function ~S has been redefined, so times may be inaccurate.~@
388                PROFILE it again to record calls to the new definition."
389               name))
390       (multiple-value-bind (calls ticks consing profile)
391           (funcall (profile-info-read-stats-fun pinfo))
392         (if (zerop calls)
393             (push name no-call-name-list)
394             (push (make-time-info :name name
395                                   :calls calls
396                                   :seconds (compensate-time calls
397                                                             ticks
398                                                             profile)
399                                   :consing consing)
400                   time-info-list))))
401
402     (setf time-info-list
403           (sort time-info-list
404                 #'>=
405                 :key #'time-info-seconds))
406
407     (format *trace-output*
408             "~&  seconds  |  consed   |  calls  |  sec/call  |  name~@
409                ------------------------------------------------------~%")
410
411     (let ((total-time 0.0)
412           (total-consed 0)
413           (total-calls 0))
414       (dolist (time-info time-info-list)
415         (incf total-time (time-info-seconds time-info))
416         (incf total-calls (time-info-calls time-info))
417         (incf total-consed (time-info-consing time-info))
418         (format *trace-output*
419                 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
420                 (time-info-seconds time-info)
421                 (time-info-consing time-info)
422                 (time-info-calls time-info)
423                 (/ (time-info-seconds time-info)
424                    (float (time-info-calls time-info)))
425                 (time-info-name time-info)))
426       (format *trace-output*
427               "------------------------------------------------------~@
428               ~10,3F | ~9:D | ~7:D |        | Total~%"
429               total-time total-consed total-calls)
430       (format *trace-output*
431               "~%estimated total profiling overhead: ~4,2F seconds~%"
432               (* (overhead-total *overhead*) (float total-calls)))
433       (format *trace-output*
434               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
435               (overhead-call *overhead*)
436               (overhead-total *overhead*)
437               (overhead-internal *overhead*)))
438
439     (when no-call-name-list
440       (format *trace-output*
441               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
442               (sort no-call-name-list #'string<
443                     :key (lambda (name)
444                            (symbol-name (function-name-block-name name))))))
445
446     (values)))
447 \f
448 ;;;; overhead estimation
449
450 ;;; We average the timing overhead over this many iterations.
451 ;;;
452 ;;; (This is a variable, not a constant, so that it can be set in
453 ;;; .sbclrc if desired. Right now, that's an unsupported extension
454 ;;; that I (WHN) use for my own experimentation, but it might
455 ;;; become supported someday. Comments?)
456 (declaim (type unsigned-byte *timer-overhead-iterations*))
457 (defparameter *timer-overhead-iterations*
458   500000)
459
460 ;;; a dummy function that we profile to find profiling overhead
461 (declaim (notinline compute-overhead-aux))
462 (defun compute-overhead-aux (x)
463   (declare (ignore x)))
464
465 ;;; Return a newly computed OVERHEAD object.
466 (defun compute-overhead ()
467   (format *debug-io* "~&measuring PROFILE overhead..")
468   (flet ((frob ()
469            (let ((start (get-internal-ticks))
470                  (fun (symbol-function 'compute-overhead-aux)))
471              (dotimes (i *timer-overhead-iterations*)
472                (funcall fun fun))
473              (/ (float (- (get-internal-ticks) start))
474                 (float +ticks-per-second+)
475                 (float *timer-overhead-iterations*)))))
476     (let (;; Measure unprofiled calls to estimate call overhead.
477           (call-overhead (frob))
478           total-overhead
479           internal-overhead)
480       ;; Measure profiled calls to estimate profiling overhead.
481       (unwind-protect
482           (progn
483             (profile compute-overhead-aux)
484             (setf total-overhead
485                   (- (frob) call-overhead)))
486         (let* ((pinfo (gethash 'compute-overhead-aux
487                                *profiled-function-name->info*))
488                (read-stats-fun (profile-info-read-stats-fun pinfo))
489                (time (nth-value 1 (funcall read-stats-fun))))
490           (setf internal-overhead
491                 (/ (float time)
492                    (float +ticks-per-second+)
493                    (float *timer-overhead-iterations*))))
494         (unprofile compute-overhead-aux))
495       (prog1
496           (make-overhead :call call-overhead
497                          :total total-overhead
498                          :internal internal-overhead)
499         (format *debug-io* "done~%")))))
500
501 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
502 ;;; then load the old *OVERHEAD* value from the .core file into a
503 ;;; different machine running at a different speed. We avoid this by
504 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
505 (pushnew (lambda ()
506            (makunbound '*overhead*))
507          *before-save-initializations*)