0.8.0.24:
[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 (fboundp symbol)
237                       (funcall function symbol))
238                     (let ((setf-name `(setf ,symbol)))
239                       (when (fboundp setf-name)
240                         (funcall function setf-name)))))))))
241   (values))
242
243 ;;; Profile the named function, which should exist and not be profiled
244 ;;; already.
245 (defun profile-1-unprofiled-fun (name)
246   (let ((encapsulated-fun (fdefinition name)))
247     (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
248         (profile-encapsulation-lambdas encapsulated-fun)
249       (setf (fdefinition name)
250             encapsulation-fun)
251       (setf (gethash name *profiled-fun-name->info*)
252             (make-profile-info :name name
253                                :encapsulated-fun encapsulated-fun
254                                :encapsulation-fun encapsulation-fun
255                                :read-stats-fun read-stats-fun
256                                :clear-stats-fun clear-stats-fun))
257       (values))))
258
259 ;;; Profile the named function. If already profiled, unprofile first.
260 (defun profile-1-fun (name)
261   (cond ((fboundp name)
262          (when (gethash name *profiled-fun-name->info*)
263            (warn "~S is already profiled, so unprofiling it first." name)
264            (unprofile-1-fun name))
265          (profile-1-unprofiled-fun name))
266         (t
267          (warn "ignoring undefined function ~S" name)))
268   (values))
269
270 ;;; Unprofile the named function, if it is profiled.
271 (defun unprofile-1-fun (name)
272   (let ((pinfo (gethash name *profiled-fun-name->info*)))
273     (cond (pinfo
274            (remhash name *profiled-fun-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   (if (null names)
297       `(loop for k being each hash-key in *profiled-fun-name->info*
298              collecting k)
299       `(mapc-on-named-funs #'profile-1-fun ',names)))
300
301 (defmacro unprofile (&rest names)
302   #+sb-doc
303   "Unwrap any profiling code around the named functions, or if no names
304   are given, unprofile all profiled functions. A symbol names
305   a function. A string names all the functions named by symbols in the
306   named package. NAMES defaults to the list of names of all currently 
307   profiled functions."
308   (if names
309       `(mapc-on-named-funs #'unprofile-1-fun ',names)
310       `(unprofile-all)))
311
312 (defun unprofile-all ()
313   (dohash (name profile-info *profiled-fun-name->info*)
314     (declare (ignore profile-info))
315     (unprofile-1-fun name)))
316
317 (defun reset ()
318   "Reset the counters for all profiled functions."
319   (dohash (name profile-info *profiled-fun-name->info*)
320     (declare (ignore name))
321     (funcall (profile-info-clear-stats-fun profile-info))))
322 \f
323 ;;;; reporting results
324
325 (defstruct (time-info (:copier nil))
326   name
327   calls
328   seconds
329   consing)
330
331 ;;; Return our best guess for the run time in a function, subtracting
332 ;;; out factors for profiling overhead. We subtract out the internal
333 ;;; overhead for each call to this function, since the internal
334 ;;; overhead is the part of the profiling overhead for a function that
335 ;;; is charged to that function.
336 ;;;
337 ;;; We also subtract out a factor for each call to a profiled function
338 ;;; within this profiled function. This factor is the total profiling
339 ;;; overhead *minus the internal overhead*. We don't subtract out the
340 ;;; internal overhead, since it was already subtracted when the nested
341 ;;; profiled functions subtracted their running time from the time for
342 ;;; the enclosing function.
343 (defun compensate-time (calls ticks profile)
344   (let ((raw-compensated
345          (- (/ (float ticks) (float +ticks-per-second+))
346             (* (overhead-internal *overhead*) (float calls))
347             (* (- (overhead-total *overhead*)
348                   (overhead-internal *overhead*))
349                (float profile)))))
350     (max raw-compensated 0.0)))
351
352 (defun report ()
353   "Report results from profiling. The results are approximately adjusted
354 for profiling overhead. The compensation may be rather inaccurate when
355 bignums are involved in runtime calculation, as in a very-long-running
356 Lisp process."
357   (unless (boundp '*overhead*)
358     (setf *overhead*
359           (compute-overhead)))
360   (let ((time-info-list ())
361         (no-call-name-list ()))
362     (dohash (name pinfo *profiled-fun-name->info*)
363       (unless (eq (fdefinition name)
364                   (profile-info-encapsulation-fun pinfo))
365         (warn "Function ~S has been redefined, so times may be inaccurate.~@
366                PROFILE it again to record calls to the new definition."
367               name))
368       (multiple-value-bind (calls ticks consing profile)
369           (funcall (profile-info-read-stats-fun pinfo))
370         (if (zerop calls)
371             (push name no-call-name-list)
372             (push (make-time-info :name name
373                                   :calls calls
374                                   :seconds (compensate-time calls
375                                                             ticks
376                                                             profile)
377                                   :consing consing)
378                   time-info-list))))
379
380     (setf time-info-list
381           (sort time-info-list
382                 #'>=
383                 :key #'time-info-seconds))
384
385     (format *trace-output*
386             "~&  seconds  |  consed   |  calls  |  sec/call  |  name~@
387                ------------------------------------------------------~%")
388
389     (let ((total-time 0.0)
390           (total-consed 0)
391           (total-calls 0))
392       (dolist (time-info time-info-list)
393         (incf total-time (time-info-seconds time-info))
394         (incf total-calls (time-info-calls time-info))
395         (incf total-consed (time-info-consing time-info))
396         (format *trace-output*
397                 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
398                 (time-info-seconds time-info)
399                 (time-info-consing time-info)
400                 (time-info-calls time-info)
401                 (/ (time-info-seconds time-info)
402                    (float (time-info-calls time-info)))
403                 (time-info-name time-info)))
404       (format *trace-output*
405               "------------------------------------------------------~@
406               ~10,3F | ~9:D | ~7:D |        | Total~%"
407               total-time total-consed total-calls)
408       (format *trace-output*
409               "~%estimated total profiling overhead: ~4,2F seconds~%"
410               (* (overhead-total *overhead*) (float total-calls)))
411       (format *trace-output*
412               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
413               (overhead-call *overhead*)
414               (overhead-total *overhead*)
415               (overhead-internal *overhead*)))
416
417     (when no-call-name-list
418       (format *trace-output*
419               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
420               (sort no-call-name-list #'string<
421                     :key (lambda (name)
422                            (symbol-name (fun-name-block-name name))))))
423
424     (values)))
425 \f
426 ;;;; overhead estimation
427
428 ;;; We average the timing overhead over this many iterations.
429 ;;;
430 ;;; (This is a variable, not a constant, so that it can be set in
431 ;;; .sbclrc if desired. Right now, that's an unsupported extension
432 ;;; that I (WHN) use for my own experimentation, but it might
433 ;;; become supported someday. Comments?)
434 (declaim (type unsigned-byte *timer-overhead-iterations*))
435 (defparameter *timer-overhead-iterations*
436   500000)
437
438 ;;; a dummy function that we profile to find profiling overhead
439 (declaim (notinline compute-overhead-aux))
440 (defun compute-overhead-aux (x)
441   (declare (ignore x)))
442
443 ;;; Return a newly computed OVERHEAD object.
444 (defun compute-overhead ()
445   (format *debug-io* "~&measuring PROFILE overhead..")
446   (flet ((frob ()
447            (let ((start (get-internal-ticks))
448                  (fun (symbol-function 'compute-overhead-aux)))
449              (declare (type function fun))
450              (dotimes (i *timer-overhead-iterations*)
451                (funcall fun fun))
452              (/ (float (- (get-internal-ticks) start))
453                 (float +ticks-per-second+)
454                 (float *timer-overhead-iterations*)))))
455     (let (;; Measure unprofiled calls to estimate call overhead.
456           (call-overhead (frob))
457           total-overhead
458           internal-overhead)
459       ;; Measure profiled calls to estimate profiling overhead.
460       (unwind-protect
461           (progn
462             (profile compute-overhead-aux)
463             (setf total-overhead
464                   (- (frob) call-overhead)))
465         (let* ((pinfo (gethash 'compute-overhead-aux
466                                *profiled-fun-name->info*))
467                (read-stats-fun (profile-info-read-stats-fun pinfo))
468                (time (nth-value 1 (funcall read-stats-fun))))
469           (setf internal-overhead
470                 (/ (float time)
471                    (float +ticks-per-second+)
472                    (float *timer-overhead-iterations*))))
473         (unprofile compute-overhead-aux))
474       (prog1
475           (make-overhead :call call-overhead
476                          :total total-overhead
477                          :internal internal-overhead)
478         (format *debug-io* "done~%")))))
479
480 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
481 ;;; then load the old *OVERHEAD* value from the .core file into a
482 ;;; different machine running at a different speed. We avoid this by
483 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
484 (pushnew (lambda ()
485            (makunbound '*overhead*))
486          *before-save-initializations*)