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