Avoid use of private typedefs
[sbcl.git] / src / code / profile.lisp
blob75591644ce1960e355aa5a4380ce369afa75ba82
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.
10 (in-package "SB-PROFILE") ; (SB-, not SB!, since we're built in warm load.)
13 ;;;; COUNTER object
14 ;;;;
15 ;;;; Thread safe, and reasonably fast: in common case increment is just an
16 ;;;; ATOMIC-INCF, in overflow case grab a lock and increment overflow counter.
18 (declaim (inline make-counter))
19 (defstruct (counter (:constructor make-counter) (:copier nil))
20 (word 0 :type sb-vm:word)
21 (overflow 0 :type unsigned-byte))
23 (defun incf-counter (counter delta)
24 ;; When running multi-threaded we can easily get negative numbers for the
25 ;; cons-counter. Don't count them at all.
26 (when (plusp delta)
27 (labels ((%incf-overflow (&optional (n 1))
28 ;; Overflow-counter can run into bignums... so we need to loop
29 ;; around CAS till the increment succeeds.
30 (loop for old = (counter-overflow counter)
31 until (eq old (compare-and-swap (counter-overflow counter)
32 old (+ old n)))))
33 (%incf (d)
34 ;; Increment the word-sized counter. If it overflows, record the
35 ;; overflow.
36 (let ((prev (atomic-incf (counter-word counter) d)))
37 (when (< (logand most-positive-word (+ prev d)) prev)
38 (%incf-overflow)))))
39 ;; DELTA can potentially be a bignum -- cut it down to word-size.
40 (unless (typep delta 'sb-vm:word)
41 (multiple-value-bind (n r) (truncate delta (1+ most-positive-word))
42 (%incf-overflow n)
43 (setf delta r)))
44 ;; ATOMIC-INCF can at most handle SIGNED-WORD: if DELTA doesn't fit that,
45 ;; DELTA/2 will.
46 (if (typep delta 'sb-vm:signed-word)
47 (%incf delta)
48 ;; ...and if delta is still too big, split it into four parts: they
49 ;; are guaranteed to fit into a signed word.
50 (multiple-value-bind (n r) (truncate delta 2)
51 (%incf n)
52 (%incf n)
53 (%incf r)))))
54 counter)
56 (defun counter-count (counter)
57 (+ (counter-word counter)
58 (* (counter-overflow counter) (1+ most-positive-word))))
60 ;;;; High resolution timer
62 ;;; FIXME: High resolution this is not. Build a microsecond-accuracy version
63 ;;; on top of unix-getrusage, maybe.
65 (defconstant +ticks-per-second+ internal-time-units-per-second)
67 (declaim (inline get-internal-ticks))
68 (defun get-internal-ticks ()
69 (get-internal-run-time))
71 ;;;; global data structures
73 ;;; We associate a PROFILE-INFO structure with each profiled function
74 ;;; name. This holds the functions that we call to manipulate the
75 ;;; closure which implements the encapsulation.
76 (defvar *profiled-fun-name->info*
77 (make-hash-table
78 ;; EQL testing isn't good enough for generalized function names
79 ;; like (SETF FOO).
80 :test 'equal
81 :synchronized t))
82 (defstruct (profile-info (:copier nil))
83 (name (missing-arg) :read-only t)
84 (encapsulated-fun (missing-arg) :type function :read-only t)
85 (encapsulation-fun (missing-arg) :type function :read-only t)
86 (read-stats-fun (missing-arg) :type function :read-only t)
87 (clear-stats-fun (missing-arg) :type function :read-only t))
89 ;;; These variables are used to subtract out the time and consing for
90 ;;; recursive and other dynamically nested profiled calls. The total
91 ;;; resource consumed for each nested call is added into the
92 ;;; appropriate variable. When the outer function returns, these
93 ;;; amounts are subtracted from the total.
94 (declaim (counter *enclosed-ticks* *enclosed-consing*))
95 (defvar *enclosed-ticks*)
96 (defvar *enclosed-consing*)
98 ;;; This variable is also used to subtract out time for nested
99 ;;; profiled calls. The time inside the profile wrapper call --
100 ;;; between its two calls to GET-INTERNAL-TICKS -- is accounted
101 ;;; for by the *ENCLOSED-TIME* variable. However, there's also extra
102 ;;; overhead involved, before we get to the first call to
103 ;;; GET-INTERNAL-TICKS, and after we get to the second call. By
104 ;;; keeping track of the count of enclosed profiled calls, we can try
105 ;;; to compensate for that.
106 (declaim (counter *enclosed-profiles*))
107 (defvar *enclosed-profiles*)
109 (declaim (counter *enclosed-gc-run-time*))
110 (defvar *enclosed-gc-run-time*)
112 ;;; the encapsulated function we're currently computing profiling data
113 ;;; for, recorded so that we can detect the problem of
114 ;;; PROFILE-computing machinery calling a function which has itself
115 ;;; been PROFILEd
116 (defvar *computing-profiling-data-for*)
118 ;;; the components of profiling overhead
119 (defstruct (overhead (:copier nil))
120 ;; the number of ticks a bare function call takes. This is
121 ;; factored into the other overheads, but not used for itself.
122 (call (missing-arg) :type single-float :read-only t)
123 ;; the number of ticks that will be charged to a profiled
124 ;; function due to the profiling code
125 (internal (missing-arg) :type single-float :read-only t)
126 ;; the number of ticks of overhead for profiling that a single
127 ;; profiled call adds to the total runtime for the program
128 (total (missing-arg) :type single-float :read-only t))
129 (defvar *overhead*)
130 (declaim (type overhead *overhead*))
131 (makunbound '*overhead*) ; in case we reload this file when tweaking
133 ;;;; profile encapsulations
135 ;;; Return a collection of closures over the same lexical context,
136 ;;; (VALUES ENCAPSULATION-FUN READ-STATS-FUN CLEAR-STATS-FUN).
138 ;;; ENCAPSULATION-FUN is a plug-in replacement for ENCAPSULATED-FUN,
139 ;;; which updates statistics whenever it's called.
141 ;;; READ-STATS-FUN returns the statistics:
142 ;;; (VALUES COUNT TIME CONSING PROFILE).
143 ;;; COUNT is the count of calls to ENCAPSULATION-FUN. TICKS is
144 ;;; the total number of ticks spent in ENCAPSULATED-FUN.
145 ;;; CONSING is the total consing of ENCAPSULATION-FUN. PROFILE is the
146 ;;; number of calls to the profiled function, stored for the purposes
147 ;;; of trying to estimate that part of profiling overhead which occurs
148 ;;; outside the interval between the profile wrapper function's timer
149 ;;; calls.
151 ;;; CLEAR-STATS-FUN clears the statistics.
153 ;;; (The reason for implementing this as coupled closures, with the
154 ;;; counts built into the lexical environment, is that we hope this
155 ;;; will minimize profiling overhead.)
156 (defun profile-encapsulation-lambdas ()
157 (declare (muffle-conditions compiler-note))
158 (let* ((count (make-counter))
159 (ticks (make-counter))
160 (consing (make-counter))
161 (profiles (make-counter))
162 (gc-run-time (make-counter)))
163 (declare (counter count ticks consing profiles gc-run-time))
164 (values
165 ;; ENCAPSULATION-FUN
166 (lambda (function &rest args)
167 (declare (optimize speed safety)
168 (function function))
169 ;; Make sure that we're not recursing infinitely.
170 (when (boundp '*computing-profiling-data-for*)
171 (unprofile-all) ; to avoid further recursion
172 (error "~@<When computing profiling data for ~S, the profiled ~
173 function ~S was called. To get out of this infinite recursion, all ~
174 functions have been unprofiled. (Since the profiling system evidently ~
175 uses ~S in its computations, it looks as though it's a bad idea to ~
176 profile it.)~:@>"
177 *computing-profiling-data-for* function function))
178 (incf-counter count 1)
179 (let ((dticks 0)
180 (dconsing 0)
181 (inner-enclosed-profiles 0)
182 (dgc-run-time 0))
183 (declare (truly-dynamic-extent dticks dconsing inner-enclosed-profiles))
184 (unwind-protect
185 (let ((start-ticks (get-internal-ticks))
186 (start-gc-run-time *gc-run-time*)
187 (*enclosed-ticks* (make-counter))
188 (*enclosed-consing* (make-counter))
189 (*enclosed-profiles* (make-counter))
190 (nbf0 *n-bytes-freed-or-purified*)
191 (dynamic-usage-0 (sb-kernel:dynamic-usage))
192 (*enclosed-gc-run-time* (make-counter)))
193 (declare (dynamic-extent *enclosed-ticks* *enclosed-consing*
194 *enclosed-profiles* *enclosed-gc-run-time*))
195 (unwind-protect
196 (apply function args)
197 (let ((*computing-profiling-data-for* function)
198 (dynamic-usage-1 (sb-kernel:dynamic-usage)))
199 (setf dticks (- (get-internal-ticks) start-ticks)
200 dconsing (if (eql *n-bytes-freed-or-purified* nbf0)
201 ;; common special case where we can avoid
202 ;; bignum arithmetic
203 (- dynamic-usage-1 dynamic-usage-0)
204 ;; general case
205 (- (get-bytes-consed) nbf0 dynamic-usage-0))
206 inner-enclosed-profiles (counter-count *enclosed-profiles*)
207 dgc-run-time (- *gc-run-time* start-gc-run-time))
208 (incf-counter ticks (- dticks (counter-count *enclosed-ticks*)))
209 (incf-counter gc-run-time (- dgc-run-time (counter-count *enclosed-gc-run-time*)))
210 (incf-counter consing (- dconsing (counter-count *enclosed-consing*)))
211 (incf-counter profiles inner-enclosed-profiles))))
212 (when (boundp '*enclosed-ticks*)
213 (incf-counter *enclosed-ticks* dticks)
214 (incf-counter *enclosed-consing* dconsing)
215 (incf-counter *enclosed-profiles* (1+ inner-enclosed-profiles))
216 (incf-counter *enclosed-gc-run-time* dgc-run-time)))))
217 ;; READ-STATS-FUN
218 (lambda ()
219 (values (counter-count count)
220 (counter-count ticks)
221 (counter-count consing)
222 (counter-count profiles)
223 (counter-count gc-run-time)))
224 ;; CLEAR-STATS-FUN
225 (lambda ()
226 (setf count (make-counter)
227 ticks (make-counter)
228 consing (make-counter)
229 profiles (make-counter)
230 gc-run-time (make-counter))))))
232 ;;;; interfaces
234 ;;; A symbol or (SETF FOO) list names a function, a string names all
235 ;;; the functions named by symbols in the named package.
236 (defun mapc-on-named-funs (function names)
237 (dolist (name names)
238 (etypecase name
239 (symbol (funcall function name))
240 (list
241 (legal-fun-name-or-type-error name)
242 ;; Then we map onto it.
243 (funcall function name))
244 (string (let ((package (find-undeleted-package-or-lose name)))
245 (do-symbols (symbol package)
246 (when (eq (symbol-package symbol) package)
247 (when (and (fboundp symbol)
248 (not (macro-function symbol))
249 (not (special-operator-p symbol)))
250 (funcall function symbol))
251 (let ((setf-name `(setf ,symbol)))
252 (when (fboundp setf-name)
253 (funcall function setf-name)))))))))
254 (values))
256 ;;; Profile the named function, which should exist and not be profiled
257 ;;; already.
258 (defun profile-1-unprofiled-fun (name)
259 (let ((encapsulated-fun (fdefinition name)))
260 (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
261 (profile-encapsulation-lambdas)
262 (without-package-locks
263 (encapsulate name 'profile encapsulation-fun))
264 (setf (gethash name *profiled-fun-name->info*)
265 (make-profile-info :name name
266 :encapsulated-fun encapsulated-fun
267 :encapsulation-fun encapsulation-fun
268 :read-stats-fun read-stats-fun
269 :clear-stats-fun clear-stats-fun))
270 (values))))
272 ;;; Profile the named function. If already profiled, unprofile first.
273 (defun profile-1-fun (name)
274 (cond ((fboundp name)
275 (when (gethash name *profiled-fun-name->info*)
276 (warn "~S is already profiled, so unprofiling it first." name)
277 (unprofile-1-fun name))
278 (profile-1-unprofiled-fun name))
280 (warn "ignoring undefined function ~S" name)))
281 (values))
283 ;;; Unprofile the named function, if it is profiled.
284 (defun unprofile-1-fun (name)
285 (let ((pinfo (gethash name *profiled-fun-name->info*)))
286 (cond (pinfo
287 (remhash name *profiled-fun-name->info*)
288 (without-package-locks
289 (unencapsulate name 'profile)))
291 (warn "~S is not a profiled function." name))))
292 (values))
294 (defmacro profile (&rest names)
295 "PROFILE Name*
297 If no names are supplied, return the list of profiled functions.
299 If names are supplied, wrap profiling code around the named functions.
300 As in TRACE, the names are not evaluated. A symbol names a function.
301 A string names all the functions named by symbols in the named
302 package. If a function is already profiled, then unprofile and
303 reprofile (useful to notice function redefinition.) If a name is
304 undefined, then we give a warning and ignore it. See also
305 UNPROFILE, REPORT and RESET."
306 (if (null names)
307 `(loop for k being each hash-key in *profiled-fun-name->info*
308 collecting k)
309 `(mapc-on-named-funs #'profile-1-fun ',names)))
311 (defmacro unprofile (&rest names)
312 "Unwrap any profiling code around the named functions, or if no names
313 are given, unprofile all profiled functions. A symbol names
314 a function. A string names all the functions named by symbols in the
315 named package. NAMES defaults to the list of names of all currently
316 profiled functions."
317 (if names
318 `(mapc-on-named-funs #'unprofile-1-fun ',names)
319 `(unprofile-all)))
321 (defun unprofile-all ()
322 (dohash ((name profile-info) *profiled-fun-name->info*
323 :locked t)
324 (declare (ignore profile-info))
325 (unprofile-1-fun name)))
327 (defun reset ()
328 "Reset the counters for all profiled functions."
329 (dohash ((name profile-info) *profiled-fun-name->info* :locked t)
330 (declare (ignore name))
331 (funcall (profile-info-clear-stats-fun profile-info))))
333 ;;;; reporting results
335 (defstruct (time-info (:copier nil))
336 name
337 calls
338 seconds
339 consing
340 gc-run-time)
342 ;;; Return our best guess for the run time in a function, subtracting
343 ;;; out factors for profiling overhead. We subtract out the internal
344 ;;; overhead for each call to this function, since the internal
345 ;;; overhead is the part of the profiling overhead for a function that
346 ;;; is charged to that function.
348 ;;; We also subtract out a factor for each call to a profiled function
349 ;;; within this profiled function. This factor is the total profiling
350 ;;; overhead *minus the internal overhead*. We don't subtract out the
351 ;;; internal overhead, since it was already subtracted when the nested
352 ;;; profiled functions subtracted their running time from the time for
353 ;;; the enclosing function.
354 (defun compensate-time (calls ticks profile)
355 (let ((raw-compensated
356 (- (/ (float ticks) (float +ticks-per-second+))
357 (* (overhead-internal *overhead*) (float calls))
358 (* (- (overhead-total *overhead*)
359 (overhead-internal *overhead*))
360 (float profile)))))
361 (max raw-compensated 0.0)))
363 (defun report (&key limit (print-no-call-list t))
364 "Report results from profiling. The results are approximately
365 adjusted for profiling overhead. The compensation may be rather
366 inaccurate when bignums are involved in runtime calculation, as in a
367 very-long-running Lisp process.
369 If LIMIT is set to an integer, only the top LIMIT results are
370 reported. If PRINT-NO-CALL-LIST is T (the default) then a list of
371 uncalled profiled functions are listed."
372 (unless (boundp '*overhead*)
373 (setf *overhead*
374 (compute-overhead)))
375 (let ((time-info-list ())
376 (no-call-name-list ()))
377 (dohash ((name pinfo) *profiled-fun-name->info* :locked t)
378 (multiple-value-bind (calls ticks consing profile gc-run-time)
379 (funcall (profile-info-read-stats-fun pinfo))
380 (if (zerop calls)
381 (push name no-call-name-list)
382 (push (make-time-info :name name
383 :calls calls
384 :seconds (compensate-time calls
385 ticks
386 profile)
387 :consing consing
388 :gc-run-time gc-run-time)
389 time-info-list))))
391 (let ((times
392 (sort time-info-list
393 #'>=
394 :key #'time-info-seconds)))
395 (print-profile-table
396 (if (and limit (> (length times) limit))
397 (subseq times 0 limit)
398 times)))
400 (when (and print-no-call-list no-call-name-list)
401 (format *trace-output*
402 "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
403 (sort no-call-name-list #'string<
404 :key (lambda (name)
405 (symbol-name (fun-name-block-name name))))))
407 (values)))
410 (defun print-profile-table (time-info-list)
411 (let ((total-seconds 0.0)
412 (total-consed 0)
413 (total-calls 0)
414 (total-gc-run-time 0)
415 (seconds-width (length "seconds"))
416 (consed-width (length "consed"))
417 (calls-width (length "calls"))
418 (sec/call-width 10)
419 (gc-run-time-width (length "gc"))
420 (name-width 6))
421 (dolist (time-info time-info-list)
422 (incf total-seconds (time-info-seconds time-info))
423 (incf total-consed (time-info-consing time-info))
424 (incf total-calls (time-info-calls time-info))
425 (incf total-gc-run-time (time-info-gc-run-time time-info)))
426 (setf seconds-width (max (length (format nil "~10,3F" total-seconds))
427 seconds-width)
428 calls-width (max (length (format nil "~:D" total-calls))
429 calls-width)
430 consed-width (max (length (format nil "~:D" total-consed))
431 consed-width)
432 gc-run-time-width (max (length (format nil "~10,3F" (/ total-gc-run-time internal-time-units-per-second)))
433 gc-run-time-width))
435 (flet ((dashes ()
436 (dotimes (i (+ seconds-width consed-width calls-width
437 sec/call-width name-width
438 (* 5 3)))
439 (write-char #\- *trace-output*))
440 (terpri *trace-output*)))
441 (format *trace-output* "~&~@{ ~v:@<~A~>~^|~}~%"
442 seconds-width "seconds"
443 (1+ gc-run-time-width) "gc"
444 (1+ consed-width) "consed"
445 (1+ calls-width) "calls"
446 (1+ sec/call-width) "sec/call"
447 (1+ name-width) "name")
449 (dashes)
451 (dolist (time-info time-info-list)
452 (format *trace-output* "~v,3F | ~v,3F | ~v:D | ~v:D | ~10,6F | ~S~%"
453 seconds-width (time-info-seconds time-info)
454 gc-run-time-width (/ (time-info-gc-run-time time-info) internal-time-units-per-second)
455 consed-width (time-info-consing time-info)
456 calls-width (time-info-calls time-info)
457 (/ (time-info-seconds time-info)
458 (float (time-info-calls time-info)))
459 (time-info-name time-info)))
461 (dashes)
463 (format *trace-output* "~v,3F | ~v,3F | ~v:D | ~v:D | | Total~%"
464 seconds-width total-seconds
465 gc-run-time-width (/ total-gc-run-time internal-time-units-per-second)
466 consed-width total-consed
467 calls-width total-calls)
469 (format *trace-output*
470 "~%estimated total profiling overhead: ~4,2F seconds~%"
471 (* (overhead-total *overhead*) (float total-calls)))
472 (format *trace-output*
473 "~&overhead estimation parameters:~% ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
474 (overhead-call *overhead*)
475 (overhead-total *overhead*)
476 (overhead-internal *overhead*)))))
479 ;;;; overhead estimation
481 ;;; We average the timing overhead over this many iterations.
483 ;;; (This is a variable, not a constant, so that it can be set in
484 ;;; .sbclrc if desired. Right now, that's an unsupported extension
485 ;;; that I (WHN) use for my own experimentation, but it might
486 ;;; become supported someday. Comments?)
487 (declaim (type unsigned-byte *timer-overhead-iterations*))
488 (defparameter *timer-overhead-iterations*
489 500000)
491 ;;; a dummy function that we profile to find profiling overhead
492 (declaim (notinline compute-overhead-aux))
493 (defun compute-overhead-aux (x)
494 (declare (ignore x)))
496 ;;; Return a newly computed OVERHEAD object.
497 (defun compute-overhead ()
498 (format *debug-io* "~&measuring PROFILE overhead..")
499 (flet ((frob ()
500 (let ((start (get-internal-ticks))
501 (fun (symbol-function 'compute-overhead-aux)))
502 (declare (type function fun))
503 (dotimes (i *timer-overhead-iterations*)
504 (funcall fun fun))
505 (/ (float (- (get-internal-ticks) start))
506 (float +ticks-per-second+)
507 (float *timer-overhead-iterations*)))))
508 (let (;; Measure unprofiled calls to estimate call overhead.
509 (call-overhead (frob))
510 total-overhead
511 internal-overhead)
512 ;; Measure profiled calls to estimate profiling overhead.
513 (unwind-protect
514 (progn
515 (profile compute-overhead-aux)
516 (setf total-overhead
517 (- (frob) call-overhead)))
518 (let* ((pinfo (gethash 'compute-overhead-aux
519 *profiled-fun-name->info*))
520 (read-stats-fun (profile-info-read-stats-fun pinfo))
521 (time (nth-value 1 (funcall read-stats-fun))))
522 (setf internal-overhead
523 (/ (float time)
524 (float +ticks-per-second+)
525 (float *timer-overhead-iterations*))))
526 (unprofile compute-overhead-aux))
527 (prog1
528 (make-overhead :call call-overhead
529 :total total-overhead
530 :internal internal-overhead)
531 (format *debug-io* "done~%")))))
533 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
534 ;;; then load the old *OVERHEAD* value from the .core file into a
535 ;;; different machine running at a different speed. We avoid this by
536 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
537 (defun profile-deinit ()
538 (without-package-locks
539 (makunbound '*overhead*)))