87eab0bbeb72357190a90ad300c91df52cc5f038
[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 inline.
102 (defmacro fastbig- (x y)
103   (once-only ((x x) (y y))
104     `(if (and (typep ,x '(and fixnum unsigned-byte))
105               (typep ,y '(and fixnum unsigned-byte)))
106          ;; special case: can use fixnum arithmetic and be guaranteed
107          ;; the result is also a fixnum
108          (- ,x ,y)
109          ;; general case
110          (- ,x ,y))))
111 (defmacro fastbig-1+ (x)
112   (once-only ((x x))
113     `(if (typep ,x 'index)
114          (1+ ,x)
115          (1+ ,x))))
116
117 ;;; Return a collection of closures over the same lexical context,
118 ;;;   (VALUES ENCAPSULATION-FUN READ-STATS-FUN CLEAR-STATS-FUN).
119 ;;;
120 ;;; ENCAPSULATION-FUN is a plug-in replacement for ENCAPSULATED-FUN,
121 ;;; which updates statistics whenver it's called.
122 ;;;
123 ;;; READ-STATS-FUN returns the statistics:
124 ;;;   (VALUES COUNT TIME CONSING PROFILE).
125 ;;; COUNT is the count of calls to ENCAPSULATION-FUN. TICKS is
126 ;;; the total number of ticks spent in ENCAPSULATED-FUN.
127 ;;; CONSING is the total consing of ENCAPSULATION-FUN. PROFILE is the
128 ;;; number of calls to the profiled function, stored for the purposes
129 ;;; of trying to estimate that part of profiling overhead which occurs
130 ;;; outside the interval between the profile wrapper function's timer
131 ;;; calls.
132 ;;;
133 ;;; CLEAR-STATS-FUN clears the statistics.
134 ;;;
135 ;;; (The reason for implementing this as coupled closures, with the
136 ;;; counts built into the lexical environment, is that we hope this
137 ;;; will minimize profiling overhead.)
138 (defun profile-encapsulation-lambdas (encapsulated-fun)
139   (declare (type function encapsulated-fun))
140   (let* ((count 0)
141          (ticks 0)
142          (consing 0)
143          (profiles 0))
144     (declare (type (or pcounter fixnum) count ticks consing profiles))
145     (values
146      ;; ENCAPSULATION-FUN
147      (lambda (&more arg-context arg-count)
148        (declare (optimize speed safety))
149        ;; Make sure that we're not recursing infinitely.
150        (when (boundp '*computing-profiling-data-for*)
151          (unprofile-all) ; to avoid further recursion
152          (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.)~:@>"
153                 *computing-profiling-data-for*
154                 encapsulated-fun
155                 encapsulated-fun))
156        ;; FIXME: Probably when this is stable, we should optimize (SAFETY 0).
157        (fastbig-incf-pcounter-or-fixnum count 1)
158        (let ((dticks 0)
159              (dconsing 0)
160              (inner-enclosed-profiles 0))
161          (declare (type unsigned-byte dticks dconsing))
162          (declare (type unsigned-byte inner-enclosed-profiles))
163          (aver (typep dticks 'unsigned-byte))
164          (aver (typep dconsing 'unsigned-byte))
165          (aver (typep inner-enclosed-profiles 'unsigned-byte))
166          (unwind-protect
167              (let* ((start-ticks (get-internal-ticks))
168                     (*enclosed-ticks* 0)
169                     (*enclosed-consing* 0)
170                     (*enclosed-profiles* 0)
171                     (nbf0 *n-bytes-freed-or-purified*)
172                     (dynamic-usage-0 (sb-kernel:dynamic-usage)))
173                (declare (inline pcounter-or-fixnum->integer))
174                (unwind-protect
175                    (multiple-value-call encapsulated-fun
176                                         (sb-c:%more-arg-values arg-context
177                                                                0
178                                                                arg-count))
179                  (let ((*computing-profiling-data-for* encapsulated-fun)
180                        (dynamic-usage-1 (sb-kernel:dynamic-usage)))
181                    (setf dticks (fastbig- (get-internal-ticks) start-ticks))
182                    (setf dconsing
183                          (if (eql *n-bytes-freed-or-purified* nbf0)
184                              ;; common special case where we can avoid
185                              ;; bignum arithmetic
186                              (- dynamic-usage-1 dynamic-usage-0)
187                              ;; general case
188                              (- (get-bytes-consed) nbf0 dynamic-usage-0)))
189                    (setf inner-enclosed-profiles
190                          (pcounter-or-fixnum->integer *enclosed-profiles*))
191                    (let ((net-dticks (fastbig- dticks *enclosed-ticks*)))
192                      (fastbig-incf-pcounter-or-fixnum ticks net-dticks))
193                    (let ((net-dconsing (fastbig- dconsing
194                                                  (pcounter-or-fixnum->integer
195                                                   *enclosed-consing*))))
196                      (fastbig-incf-pcounter-or-fixnum consing net-dconsing))
197                    (fastbig-incf-pcounter-or-fixnum profiles
198                                                     inner-enclosed-profiles))))
199            (fastbig-incf-pcounter-or-fixnum *enclosed-ticks* dticks)
200            (fastbig-incf-pcounter-or-fixnum *enclosed-consing* dconsing)
201            (fastbig-incf-pcounter-or-fixnum *enclosed-profiles*
202                                             (fastbig-1+
203                                              inner-enclosed-profiles)))))
204      ;; READ-STATS-FUN
205      (lambda ()
206        (values (pcounter-or-fixnum->integer count)
207                (pcounter-or-fixnum->integer ticks)
208                (pcounter-or-fixnum->integer consing)
209                (pcounter-or-fixnum->integer profiles)))
210      ;; CLEAR-STATS-FUN
211      (lambda ()
212        (setf count 0
213              ticks 0
214              consing 0
215              profiles 0)))))
216 \f
217 ;;;; interfaces
218
219 ;;; A symbol or (SETF FOO) list names a function, a string names all
220 ;;; the functions named by symbols in the named package.
221 (defun mapc-on-named-funs (function names)
222   (dolist (name names)
223     (etypecase name
224       (symbol (funcall function name))
225       (list
226        (legal-fun-name-or-type-error name)
227        ;; Then we map onto it.
228        (funcall function name))
229       (string (let ((package (find-undeleted-package-or-lose name)))
230                 (do-symbols (symbol package)
231                   (when (eq (symbol-package symbol) package)
232                     (when (fboundp symbol)
233                       (funcall function symbol))
234                     (let ((setf-name `(setf ,symbol)))
235                       (when (fboundp setf-name)
236                         (funcall function setf-name)))))))))
237   (values))
238
239 ;;; Profile the named function, which should exist and not be profiled
240 ;;; already.
241 (defun profile-1-unprofiled-fun (name)
242   (let ((encapsulated-fun (fdefinition name)))
243     (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
244         (profile-encapsulation-lambdas encapsulated-fun)
245       (setf (fdefinition name)
246             encapsulation-fun)
247       (setf (gethash name *profiled-fun-name->info*)
248             (make-profile-info :name name
249                                :encapsulated-fun encapsulated-fun
250                                :encapsulation-fun encapsulation-fun
251                                :read-stats-fun read-stats-fun
252                                :clear-stats-fun clear-stats-fun))
253       (values))))
254
255 ;;; Profile the named function. If already profiled, unprofile first.
256 (defun profile-1-fun (name)
257   (cond ((fboundp name)
258          (when (gethash name *profiled-fun-name->info*)
259            (warn "~S is already profiled, so unprofiling it first." name)
260            (unprofile-1-fun name))
261          (profile-1-unprofiled-fun name))
262         (t
263          (warn "ignoring undefined function ~S" name)))
264   (values))
265
266 ;;; Unprofile the named function, if it is profiled.
267 (defun unprofile-1-fun (name)
268   (let ((pinfo (gethash name *profiled-fun-name->info*)))
269     (cond (pinfo
270            (remhash name *profiled-fun-name->info*)
271            (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
272                (setf (fdefinition name) (profile-info-encapsulated-fun pinfo))
273                (warn "preserving current definition of redefined function ~S"
274                      name)))
275           (t
276            (warn "~S is not a profiled function." name))))
277   (values))
278
279 (defmacro profile (&rest names)
280   #+sb-doc
281   "PROFILE Name*
282
283    If no names are supplied, return the list of profiled functions.
284
285    If names are supplied, wrap profiling code around the named functions.
286    As in TRACE, the names are not evaluated. A symbol names a function.
287    A string names all the functions named by symbols in the named
288    package. If a function is already profiled, then unprofile and
289    reprofile (useful to notice function redefinition.)  If a name is
290    undefined, then we give a warning and ignore it. See also
291    UNPROFILE, REPORT and RESET."
292   (if (null names)
293       `(loop for k being each hash-key in *profiled-fun-name->info*
294              collecting k)
295       `(mapc-on-named-funs #'profile-1-fun ',names)))
296
297 (defmacro unprofile (&rest names)
298   #+sb-doc
299   "Unwrap any profiling code around the named functions, or if no names
300   are given, unprofile all profiled functions. A symbol names
301   a function. A string names all the functions named by symbols in the
302   named package. NAMES defaults to the list of names of all currently 
303   profiled functions."
304   (if names
305       `(mapc-on-named-funs #'unprofile-1-fun ',names)
306       `(unprofile-all)))
307
308 (defun unprofile-all ()
309   (dohash (name profile-info *profiled-fun-name->info*)
310     (declare (ignore profile-info))
311     (unprofile-1-fun name)))
312
313 (defun reset ()
314   "Reset the counters for all profiled functions."
315   (dohash (name profile-info *profiled-fun-name->info*)
316     (declare (ignore name))
317     (funcall (profile-info-clear-stats-fun profile-info))))
318 \f
319 ;;;; reporting results
320
321 (defstruct (time-info (:copier nil))
322   name
323   calls
324   seconds
325   consing)
326
327 ;;; Return our best guess for the run time in a function, subtracting
328 ;;; out factors for profiling overhead. We subtract out the internal
329 ;;; overhead for each call to this function, since the internal
330 ;;; overhead is the part of the profiling overhead for a function that
331 ;;; is charged to that function.
332 ;;;
333 ;;; We also subtract out a factor for each call to a profiled function
334 ;;; within this profiled function. This factor is the total profiling
335 ;;; overhead *minus the internal overhead*. We don't subtract out the
336 ;;; internal overhead, since it was already subtracted when the nested
337 ;;; profiled functions subtracted their running time from the time for
338 ;;; the enclosing function.
339 (defun compensate-time (calls ticks profile)
340   (let ((raw-compensated
341          (- (/ (float ticks) (float +ticks-per-second+))
342             (* (overhead-internal *overhead*) (float calls))
343             (* (- (overhead-total *overhead*)
344                   (overhead-internal *overhead*))
345                (float profile)))))
346     (max raw-compensated 0.0)))
347
348 (defun report ()
349   "Report results from profiling. The results are approximately adjusted
350 for profiling overhead. The compensation may be rather inaccurate when
351 bignums are involved in runtime calculation, as in a very-long-running
352 Lisp process."
353   (unless (boundp '*overhead*)
354     (setf *overhead*
355           (compute-overhead)))
356   (let ((time-info-list ())
357         (no-call-name-list ()))
358     (dohash (name pinfo *profiled-fun-name->info*)
359       (unless (eq (fdefinition name)
360                   (profile-info-encapsulation-fun pinfo))
361         (warn "Function ~S has been redefined, so times may be inaccurate.~@
362                PROFILE it again to record calls to the new definition."
363               name))
364       (multiple-value-bind (calls ticks consing profile)
365           (funcall (profile-info-read-stats-fun pinfo))
366         (if (zerop calls)
367             (push name no-call-name-list)
368             (push (make-time-info :name name
369                                   :calls calls
370                                   :seconds (compensate-time calls
371                                                             ticks
372                                                             profile)
373                                   :consing consing)
374                   time-info-list))))
375
376     (setf time-info-list
377           (sort time-info-list
378                 #'>=
379                 :key #'time-info-seconds))
380
381     (format *trace-output*
382             "~&  seconds  |  consed   |  calls  |  sec/call  |  name~@
383                ------------------------------------------------------~%")
384
385     (let ((total-time 0.0)
386           (total-consed 0)
387           (total-calls 0))
388       (dolist (time-info time-info-list)
389         (incf total-time (time-info-seconds time-info))
390         (incf total-calls (time-info-calls time-info))
391         (incf total-consed (time-info-consing time-info))
392         (format *trace-output*
393                 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
394                 (time-info-seconds time-info)
395                 (time-info-consing time-info)
396                 (time-info-calls time-info)
397                 (/ (time-info-seconds time-info)
398                    (float (time-info-calls time-info)))
399                 (time-info-name time-info)))
400       (format *trace-output*
401               "------------------------------------------------------~@
402               ~10,3F | ~9:D | ~7:D |        | Total~%"
403               total-time total-consed total-calls)
404       (format *trace-output*
405               "~%estimated total profiling overhead: ~4,2F seconds~%"
406               (* (overhead-total *overhead*) (float total-calls)))
407       (format *trace-output*
408               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
409               (overhead-call *overhead*)
410               (overhead-total *overhead*)
411               (overhead-internal *overhead*)))
412
413     (when no-call-name-list
414       (format *trace-output*
415               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
416               (sort no-call-name-list #'string<
417                     :key (lambda (name)
418                            (symbol-name (fun-name-block-name name))))))
419
420     (values)))
421 \f
422 ;;;; overhead estimation
423
424 ;;; We average the timing overhead over this many iterations.
425 ;;;
426 ;;; (This is a variable, not a constant, so that it can be set in
427 ;;; .sbclrc if desired. Right now, that's an unsupported extension
428 ;;; that I (WHN) use for my own experimentation, but it might
429 ;;; become supported someday. Comments?)
430 (declaim (type unsigned-byte *timer-overhead-iterations*))
431 (defparameter *timer-overhead-iterations*
432   500000)
433
434 ;;; a dummy function that we profile to find profiling overhead
435 (declaim (notinline compute-overhead-aux))
436 (defun compute-overhead-aux (x)
437   (declare (ignore x)))
438
439 ;;; Return a newly computed OVERHEAD object.
440 (defun compute-overhead ()
441   (format *debug-io* "~&measuring PROFILE overhead..")
442   (flet ((frob ()
443            (let ((start (get-internal-ticks))
444                  (fun (symbol-function 'compute-overhead-aux)))
445              (declare (type function fun))
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*)