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