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