1.0.11.22: hash-table synchronization support
[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 (defconstant +ticks-per-second+ internal-time-units-per-second)
15
16 (declaim (inline get-internal-ticks))
17 (defun get-internal-ticks () (get-internal-run-time))
18 \f
19 ;;;; implementation-dependent interfaces
20
21 #|
22 ;;; To avoid unnecessary consing in the "encapsulation" code, we want
23 ;;; find out the number of required arguments, and use &REST to
24 ;;; capture only non-required arguments. This function returns (VALUES
25 ;;; MIN-ARGS OPTIONALS-P), where MIN-ARGS is the number of required
26 ;;; arguments and OPTIONALS-P is true iff there are any non-required
27 ;;; arguments (such as &OPTIONAL, &REST, or &KEY).
28 (declaim (ftype (function ((or symbol cons)) (values fixnum t)) fun-signature))
29 (defun fun-signature (name)
30   (let ((type (info :function :type name)))
31     (cond ((not (fun-type-p type))
32            (values 0 t))
33           (t
34            (values (length (fun-type-required type))
35                    (or (fun-type-optional type)
36                        (fun-type-keyp type)
37                        (fun-type-rest type)))))))
38 |#
39 \f
40 ;;;; global data structures
41
42 ;;; We associate a PROFILE-INFO structure with each profiled function
43 ;;; name. This holds the functions that we call to manipulate the
44 ;;; closure which implements the encapsulation.
45 (defvar *profiled-fun-name->info*
46   (make-hash-table
47    ;; EQL testing isn't good enough for generalized function names
48    ;; like (SETF FOO).
49    :test 'equal))
50 (defstruct (profile-info (:copier nil))
51   (name              (missing-arg) :read-only t)
52   (encapsulated-fun  (missing-arg) :type function :read-only t)
53   (encapsulation-fun (missing-arg) :type function :read-only t)
54   (read-stats-fun    (missing-arg) :type function :read-only t)
55   (clear-stats-fun   (missing-arg) :type function :read-only t))
56
57 ;;; These variables are used to subtract out the time and consing for
58 ;;; recursive and other dynamically nested profiled calls. The total
59 ;;; resource consumed for each nested call is added into the
60 ;;; appropriate variable. When the outer function returns, these
61 ;;; amounts are subtracted from the total.
62 (defvar *enclosed-ticks* 0)
63 (defvar *enclosed-consing* 0)
64 (declaim (type (or pcounter fixnum) *enclosed-ticks* *enclosed-consing*))
65
66 ;;; This variable is also used to subtract out time for nested
67 ;;; profiled calls. The time inside the profile wrapper call --
68 ;;; between its two calls to GET-INTERNAL-TICKS -- is accounted
69 ;;; for by the *ENCLOSED-TIME* variable. However, there's also extra
70 ;;; overhead involved, before we get to the first call to
71 ;;; GET-INTERNAL-TICKS, and after we get to the second call. By
72 ;;; keeping track of the count of enclosed profiled calls, we can try
73 ;;; to compensate for that.
74 (defvar *enclosed-profiles* 0)
75 (declaim (type (or pcounter fixnum) *enclosed-profiles*))
76
77 ;;; the encapsulated function we're currently computing profiling data
78 ;;; for, recorded so that we can detect the problem of
79 ;;; PROFILE-computing machinery calling a function which has itself
80 ;;; been PROFILEd
81 (defvar *computing-profiling-data-for*)
82
83 ;;; the components of profiling overhead
84 (defstruct (overhead (:copier nil))
85   ;; the number of ticks a bare function call takes. This is
86   ;; factored into the other overheads, but not used for itself.
87   (call (missing-arg) :type single-float :read-only t)
88   ;; the number of ticks that will be charged to a profiled
89   ;; function due to the profiling code
90   (internal (missing-arg) :type single-float :read-only t)
91   ;; the number of ticks of overhead for profiling that a single
92   ;; profiled call adds to the total runtime for the program
93   (total (missing-arg) :type single-float :read-only t))
94 (defvar *overhead*)
95 (declaim (type overhead *overhead*))
96 (makunbound '*overhead*) ; in case we reload this file when tweaking
97 \f
98 ;;;; profile encapsulations
99
100 ;;; Trade off space for time by handling the usual all-FIXNUM cases inline.
101 (defmacro fastbig- (x y)
102   (once-only ((x x) (y y))
103     `(if (and (typep ,x '(and fixnum unsigned-byte))
104               (typep ,y '(and fixnum unsigned-byte)))
105          ;; special case: can use fixnum arithmetic and be guaranteed
106          ;; the result is also a fixnum
107          (- ,x ,y)
108          ;; general case
109          (- ,x ,y))))
110 (defmacro fastbig-1+ (x)
111   (once-only ((x x))
112     `(if (typep ,x 'index)
113          (1+ ,x)
114          (1+ ,x))))
115
116 ;;; Return a collection of closures over the same lexical context,
117 ;;;   (VALUES ENCAPSULATION-FUN READ-STATS-FUN CLEAR-STATS-FUN).
118 ;;;
119 ;;; ENCAPSULATION-FUN is a plug-in replacement for ENCAPSULATED-FUN,
120 ;;; which updates statistics whenever it's called.
121 ;;;
122 ;;; READ-STATS-FUN returns the statistics:
123 ;;;   (VALUES COUNT TIME CONSING PROFILE).
124 ;;; COUNT is the count of calls to ENCAPSULATION-FUN. TICKS is
125 ;;; the total number of ticks spent in ENCAPSULATED-FUN.
126 ;;; CONSING is the total consing of ENCAPSULATION-FUN. PROFILE is the
127 ;;; number of calls to the profiled function, stored for the purposes
128 ;;; of trying to estimate that part of profiling overhead which occurs
129 ;;; outside the interval between the profile wrapper function's timer
130 ;;; calls.
131 ;;;
132 ;;; CLEAR-STATS-FUN clears the statistics.
133 ;;;
134 ;;; (The reason for implementing this as coupled closures, with the
135 ;;; counts built into the lexical environment, is that we hope this
136 ;;; will minimize profiling overhead.)
137 (defun profile-encapsulation-lambdas (encapsulated-fun)
138   (declare (type function encapsulated-fun))
139   (let* ((count 0)
140          (ticks 0)
141          (consing 0)
142          (profiles 0))
143     (declare (type (or pcounter fixnum) count ticks consing profiles))
144     (values
145      ;; ENCAPSULATION-FUN
146      (lambda (&more arg-context arg-count)
147        (declare (optimize speed safety))
148        ;; Make sure that we're not recursing infinitely.
149        (when (boundp '*computing-profiling-data-for*)
150          (unprofile-all) ; to avoid further recursion
151          (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.)~:@>"
152                 *computing-profiling-data-for*
153                 encapsulated-fun
154                 encapsulated-fun))
155        ;; FIXME: Probably when this is stable, we should optimize (SAFETY 0).
156        (fastbig-incf-pcounter-or-fixnum count 1)
157        (let ((dticks 0)
158              (dconsing 0)
159              (inner-enclosed-profiles 0))
160          (declare (type unsigned-byte dticks dconsing))
161          (declare (type unsigned-byte inner-enclosed-profiles))
162          (aver (typep dticks 'unsigned-byte))
163          (aver (typep dconsing 'unsigned-byte))
164          (aver (typep inner-enclosed-profiles 'unsigned-byte))
165          (unwind-protect
166              (let* ((start-ticks (get-internal-ticks))
167                     (*enclosed-ticks* 0)
168                     (*enclosed-consing* 0)
169                     (*enclosed-profiles* 0)
170                     (nbf0 *n-bytes-freed-or-purified*)
171                     (dynamic-usage-0 (sb-kernel:dynamic-usage)))
172                (declare (inline pcounter-or-fixnum->integer))
173                (unwind-protect
174                    (multiple-value-call encapsulated-fun
175                                         (sb-c:%more-arg-values arg-context
176                                                                0
177                                                                arg-count))
178                  (let ((*computing-profiling-data-for* encapsulated-fun)
179                        (dynamic-usage-1 (sb-kernel:dynamic-usage)))
180                    (setf dticks (fastbig- (get-internal-ticks) start-ticks))
181                    (setf dconsing
182                          (if (eql *n-bytes-freed-or-purified* nbf0)
183                              ;; common special case where we can avoid
184                              ;; bignum arithmetic
185                              (- dynamic-usage-1 dynamic-usage-0)
186                              ;; general case
187                              (- (get-bytes-consed) nbf0 dynamic-usage-0)))
188                    (setf inner-enclosed-profiles
189                          (pcounter-or-fixnum->integer *enclosed-profiles*))
190                    (let ((net-dticks (fastbig- dticks *enclosed-ticks*)))
191                      (fastbig-incf-pcounter-or-fixnum ticks net-dticks))
192                    (let ((net-dconsing (fastbig- dconsing
193                                                  (pcounter-or-fixnum->integer
194                                                   *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-funs (function names)
221   (dolist (name names)
222     (etypecase name
223       (symbol (funcall function name))
224       (list
225        (legal-fun-name-or-type-error name)
226        ;; Then we map onto it.
227        (funcall function name))
228       (string (let ((package (find-undeleted-package-or-lose name)))
229                 (do-symbols (symbol package)
230                   (when (eq (symbol-package symbol) package)
231                     (when (and (fboundp symbol)
232                                (not (macro-function symbol))
233                                (not (special-operator-p 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-fun (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       (without-package-locks
247        (setf (fdefinition name)
248              encapsulation-fun))
249       (setf (gethash name *profiled-fun-name->info*)
250             (make-profile-info :name name
251                                :encapsulated-fun encapsulated-fun
252                                :encapsulation-fun encapsulation-fun
253                                :read-stats-fun read-stats-fun
254                                :clear-stats-fun clear-stats-fun))
255       (values))))
256
257 ;;; Profile the named function. If already profiled, unprofile first.
258 (defun profile-1-fun (name)
259   (cond ((fboundp name)
260          (when (gethash name *profiled-fun-name->info*)
261            (warn "~S is already profiled, so unprofiling it first." name)
262            (unprofile-1-fun name))
263          (profile-1-unprofiled-fun name))
264         (t
265          (warn "ignoring undefined function ~S" name)))
266   (values))
267
268 ;;; Unprofile the named function, if it is profiled.
269 (defun unprofile-1-fun (name)
270   (let ((pinfo (gethash name *profiled-fun-name->info*)))
271     (cond (pinfo
272            (remhash name *profiled-fun-name->info*)
273            (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
274                (without-package-locks
275                 (setf (fdefinition name) (profile-info-encapsulated-fun pinfo)))
276                (warn "preserving current definition of redefined function ~S"
277                      name)))
278           (t
279            (warn "~S is not a profiled function." name))))
280   (values))
281
282 (defmacro profile (&rest names)
283   #+sb-doc
284   "PROFILE Name*
285
286    If no names are supplied, return the list of profiled functions.
287
288    If names are supplied, wrap profiling code around the named functions.
289    As in TRACE, the names are not evaluated. A symbol names a function.
290    A string names all the functions named by symbols in the named
291    package. If a function is already profiled, then unprofile and
292    reprofile (useful to notice function redefinition.)  If a name is
293    undefined, then we give a warning and ignore it. See also
294    UNPROFILE, REPORT and RESET."
295   (if (null names)
296       `(loop for k being each hash-key in *profiled-fun-name->info*
297              collecting k)
298       `(mapc-on-named-funs #'profile-1-fun ',names)))
299
300 (defmacro unprofile (&rest names)
301   #+sb-doc
302   "Unwrap any profiling code around the named functions, or if no names
303   are given, unprofile all profiled functions. A symbol names
304   a function. A string names all the functions named by symbols in the
305   named package. NAMES defaults to the list of names of all currently
306   profiled functions."
307   (if names
308       `(mapc-on-named-funs #'unprofile-1-fun ',names)
309       `(unprofile-all)))
310
311 (defun unprofile-all ()
312   (dohash ((name profile-info) *profiled-fun-name->info*
313            :locked t)
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* :locked t)
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* :locked t)
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     (print-profile-table time-info-list)
385
386     (when no-call-name-list
387       (format *trace-output*
388               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
389               (sort no-call-name-list #'string<
390                     :key (lambda (name)
391                            (symbol-name (fun-name-block-name name))))))
392
393     (values)))
394
395
396 (defun print-profile-table (time-info-list)
397   (let ((total-seconds 0.0)
398         (total-consed 0)
399         (total-calls 0)
400         (seconds-width (length "seconds"))
401         (consed-width (length "consed"))
402         (calls-width (length "calls"))
403         (sec/call-width 10)
404         (name-width 6))
405     (dolist (time-info time-info-list)
406       (incf total-seconds (time-info-seconds time-info))
407       (incf total-consed (time-info-consing time-info))
408       (incf total-calls (time-info-calls time-info)))
409     (setf seconds-width (max (length (format nil "~10,3F" total-seconds))
410                              seconds-width)
411           calls-width (max (length (format nil "~:D" total-calls))
412                            calls-width)
413           consed-width (max (length (format nil "~:D" total-consed))
414                             consed-width))
415
416     (flet ((dashes ()
417              (dotimes (i (+ seconds-width consed-width calls-width
418                             sec/call-width name-width
419                             (* 5 3)))
420                (write-char #\- *trace-output*))
421              (terpri *trace-output*)))
422       (format *trace-output* "~&~@{ ~v:@<~A~>~^|~}~%"
423               seconds-width "seconds"
424               (1+ consed-width) "consed"
425               (1+ calls-width) "calls"
426               (1+ sec/call-width) "sec/call"
427               (1+ name-width) "name")
428
429       (dashes)
430
431       (dolist (time-info time-info-list)
432         (format *trace-output* "~v,3F | ~v:D | ~v:D | ~10,6F | ~S~%"
433                 seconds-width (time-info-seconds time-info)
434                 consed-width (time-info-consing time-info)
435                 calls-width (time-info-calls time-info)
436                 (/ (time-info-seconds time-info)
437                    (float (time-info-calls time-info)))
438                 (time-info-name time-info)))
439
440       (dashes)
441
442       (format *trace-output* "~v,3F | ~v:D | ~v:D |            | Total~%"
443                 seconds-width total-seconds
444                 consed-width total-consed
445                 calls-width total-calls)
446
447       (format *trace-output*
448               "~%estimated total profiling overhead: ~4,2F seconds~%"
449               (* (overhead-total *overhead*) (float total-calls)))
450       (format *trace-output*
451               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
452               (overhead-call *overhead*)
453               (overhead-total *overhead*)
454               (overhead-internal *overhead*)))))
455
456 \f
457 ;;;; overhead estimation
458
459 ;;; We average the timing overhead over this many iterations.
460 ;;;
461 ;;; (This is a variable, not a constant, so that it can be set in
462 ;;; .sbclrc if desired. Right now, that's an unsupported extension
463 ;;; that I (WHN) use for my own experimentation, but it might
464 ;;; become supported someday. Comments?)
465 (declaim (type unsigned-byte *timer-overhead-iterations*))
466 (defparameter *timer-overhead-iterations*
467   500000)
468
469 ;;; a dummy function that we profile to find profiling overhead
470 (declaim (notinline compute-overhead-aux))
471 (defun compute-overhead-aux (x)
472   (declare (ignore x)))
473
474 ;;; Return a newly computed OVERHEAD object.
475 (defun compute-overhead ()
476   (format *debug-io* "~&measuring PROFILE overhead..")
477   (flet ((frob ()
478            (let ((start (get-internal-ticks))
479                  (fun (symbol-function 'compute-overhead-aux)))
480              (declare (type function fun))
481              (dotimes (i *timer-overhead-iterations*)
482                (funcall fun fun))
483              (/ (float (- (get-internal-ticks) start))
484                 (float +ticks-per-second+)
485                 (float *timer-overhead-iterations*)))))
486     (let (;; Measure unprofiled calls to estimate call overhead.
487           (call-overhead (frob))
488           total-overhead
489           internal-overhead)
490       ;; Measure profiled calls to estimate profiling overhead.
491       (unwind-protect
492           (progn
493             (profile compute-overhead-aux)
494             (setf total-overhead
495                   (- (frob) call-overhead)))
496         (let* ((pinfo (gethash 'compute-overhead-aux
497                                *profiled-fun-name->info*))
498                (read-stats-fun (profile-info-read-stats-fun pinfo))
499                (time (nth-value 1 (funcall read-stats-fun))))
500           (setf internal-overhead
501                 (/ (float time)
502                    (float +ticks-per-second+)
503                    (float *timer-overhead-iterations*))))
504         (unprofile compute-overhead-aux))
505       (prog1
506           (make-overhead :call call-overhead
507                          :total total-overhead
508                          :internal internal-overhead)
509         (format *debug-io* "done~%")))))
510
511 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
512 ;;; then load the old *OVERHEAD* value from the .core file into a
513 ;;; different machine running at a different speed. We avoid this by
514 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
515 (defun profile-deinit ()
516   (without-package-locks
517     (makunbound '*overhead*)))