1 ;;;; This software is part of the SBCL system. See the README file for
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.)
12 ;;;; reading internal run time with high resolution and low overhead
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.
19 (defconstant +ticks-per-second+ internal-time-units-per-second)
21 (declaim (inline get-internal-ticks))
22 (defun get-internal-ticks () (get-internal-run-time))
24 ;;;; implementation-dependent interfaces
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))
39 (values (length (fun-type-required type))
40 (or (fun-type-optional type)
42 (fun-type-rest type)))))))
45 ;;;; global data structures
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*
52 ;; EQL testing isn't good enough for generalized function names
55 (defstruct (profile-info (:copier nil))
56 (name (missing-arg) :read-only t)
57 (encapsulated-fun (missing-arg) :type function :read-only t)
58 (encapsulation-fun (missing-arg) :type function :read-only t)
59 (read-stats-fun (missing-arg) :type function :read-only t)
60 (clear-stats-fun (missing-arg) :type function :read-only t))
62 ;;; These variables are used to subtract out the time and consing for
63 ;;; recursive and other dynamically nested profiled calls. The total
64 ;;; resource consumed for each nested call is added into the
65 ;;; appropriate variable. When the outer function returns, these
66 ;;; amounts are subtracted from the total.
67 (defvar *enclosed-ticks* 0)
68 (defvar *enclosed-consing* 0)
69 (declaim (type (or pcounter fixnum) *enclosed-ticks* *enclosed-consing*))
71 ;;; This variable is also used to subtract out time for nested
72 ;;; profiled calls. The time inside the profile wrapper call --
73 ;;; between its two calls to GET-INTERNAL-TICKS -- is accounted
74 ;;; for by the *ENCLOSED-TIME* variable. However, there's also extra
75 ;;; overhead involved, before we get to the first call to
76 ;;; GET-INTERNAL-TICKS, and after we get to the second call. By
77 ;;; keeping track of the count of enclosed profiled calls, we can try
78 ;;; to compensate for that.
79 (defvar *enclosed-profiles* 0)
80 (declaim (type (or pcounter fixnum) *enclosed-profiles*))
82 ;;; the encapsulated function we're currently computing profiling data
83 ;;; for, recorded so that we can detect the problem of
84 ;;; PROFILE-computing machinery calling a function which has itself
86 (defvar *computing-profiling-data-for*)
88 ;;; the components of profiling overhead
89 (defstruct (overhead (:copier nil))
90 ;; the number of ticks a bare function call takes. This is
91 ;; factored into the other overheads, but not used for itself.
92 (call (missing-arg) :type single-float :read-only t)
93 ;; the number of ticks that will be charged to a profiled
94 ;; function due to the profiling code
95 (internal (missing-arg) :type single-float :read-only t)
96 ;; the number of ticks of overhead for profiling that a single
97 ;; profiled call adds to the total runtime for the program
98 (total (missing-arg) :type single-float :read-only t))
100 (declaim (type overhead *overhead*))
101 (makunbound '*overhead*) ; in case we reload this file when tweaking
103 ;;;; profile encapsulations
105 ;;; Trade off space for time by handling the usual all-FIXNUM cases inline.
106 (defmacro fastbig- (x y)
107 (once-only ((x x) (y y))
108 `(if (and (typep ,x '(and fixnum unsigned-byte))
109 (typep ,y '(and fixnum unsigned-byte)))
110 ;; special case: can use fixnum arithmetic and be guaranteed
111 ;; the result is also a fixnum
115 (defmacro fastbig-1+ (x)
117 `(if (typep ,x 'index)
121 ;;; Return a collection of closures over the same lexical context,
122 ;;; (VALUES ENCAPSULATION-FUN READ-STATS-FUN CLEAR-STATS-FUN).
124 ;;; ENCAPSULATION-FUN is a plug-in replacement for ENCAPSULATED-FUN,
125 ;;; which updates statistics whenver it's called.
127 ;;; READ-STATS-FUN returns the statistics:
128 ;;; (VALUES COUNT TIME CONSING PROFILE).
129 ;;; COUNT is the count of calls to ENCAPSULATION-FUN. TICKS is
130 ;;; the total number of ticks spent in ENCAPSULATED-FUN.
131 ;;; CONSING is the total consing of ENCAPSULATION-FUN. PROFILE is the
132 ;;; number of calls to the profiled function, stored for the purposes
133 ;;; of trying to estimate that part of profiling overhead which occurs
134 ;;; outside the interval between the profile wrapper function's timer
137 ;;; CLEAR-STATS-FUN clears the statistics.
139 ;;; (The reason for implementing this as coupled closures, with the
140 ;;; counts built into the lexical environment, is that we hope this
141 ;;; will minimize profiling overhead.)
142 (defun profile-encapsulation-lambdas (encapsulated-fun)
143 (declare (type function encapsulated-fun))
148 (declare (type (or pcounter fixnum) count ticks consing profiles))
151 (lambda (&more arg-context arg-count)
152 (declare (optimize speed safety))
153 ;; Make sure that we're not recursing infinitely.
154 (when (boundp '*computing-profiling-data-for*)
155 (unprofile-all) ; to avoid further recursion
156 (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.)~:@>"
157 *computing-profiling-data-for*
160 ;; FIXME: Probably when this is stable, we should optimize (SAFETY 0).
161 (fastbig-incf-pcounter-or-fixnum count 1)
164 (inner-enclosed-profiles 0))
165 (declare (type unsigned-byte dticks dconsing))
166 (declare (type unsigned-byte inner-enclosed-profiles))
167 (aver (typep dticks 'unsigned-byte))
168 (aver (typep dconsing 'unsigned-byte))
169 (aver (typep inner-enclosed-profiles 'unsigned-byte))
171 (let* ((start-ticks (get-internal-ticks))
173 (*enclosed-consing* 0)
174 (*enclosed-profiles* 0)
175 (nbf0 *n-bytes-freed-or-purified*)
176 (dynamic-usage-0 (sb-kernel:dynamic-usage)))
177 (declare (inline pcounter-or-fixnum->integer))
179 (multiple-value-call encapsulated-fun
180 (sb-c:%more-arg-values arg-context
183 (let ((*computing-profiling-data-for* encapsulated-fun)
184 (dynamic-usage-1 (sb-kernel:dynamic-usage)))
185 (setf dticks (fastbig- (get-internal-ticks) start-ticks))
187 (if (eql *n-bytes-freed-or-purified* nbf0)
188 ;; common special case where we can avoid
190 (- dynamic-usage-1 dynamic-usage-0)
192 (- (get-bytes-consed) nbf0 dynamic-usage-0)))
193 (setf inner-enclosed-profiles
194 (pcounter-or-fixnum->integer *enclosed-profiles*))
195 (let ((net-dticks (fastbig- dticks *enclosed-ticks*)))
196 (fastbig-incf-pcounter-or-fixnum ticks net-dticks))
197 (let ((net-dconsing (fastbig- dconsing
198 (pcounter-or-fixnum->integer
199 *enclosed-consing*))))
200 (fastbig-incf-pcounter-or-fixnum consing net-dconsing))
201 (fastbig-incf-pcounter-or-fixnum profiles
202 inner-enclosed-profiles))))
203 (fastbig-incf-pcounter-or-fixnum *enclosed-ticks* dticks)
204 (fastbig-incf-pcounter-or-fixnum *enclosed-consing* dconsing)
205 (fastbig-incf-pcounter-or-fixnum *enclosed-profiles*
207 inner-enclosed-profiles)))))
210 (values (pcounter-or-fixnum->integer count)
211 (pcounter-or-fixnum->integer ticks)
212 (pcounter-or-fixnum->integer consing)
213 (pcounter-or-fixnum->integer profiles)))
223 ;;; A symbol or (SETF FOO) list names a function, a string names all
224 ;;; the functions named by symbols in the named package.
225 (defun mapc-on-named-funs (function names)
228 (symbol (funcall function name))
230 (legal-fun-name-or-type-error name)
231 ;; Then we map onto it.
232 (funcall function name))
233 (string (let ((package (find-undeleted-package-or-lose name)))
234 (do-symbols (symbol package)
235 (when (eq (symbol-package symbol) package)
236 (when (and (fboundp symbol)
237 (not (macro-function symbol))
238 (not (special-operator-p symbol)))
239 (funcall function symbol))
240 (let ((setf-name `(setf ,symbol)))
241 (when (fboundp setf-name)
242 (funcall function setf-name)))))))))
245 ;;; Profile the named function, which should exist and not be profiled
247 (defun profile-1-unprofiled-fun (name)
248 (let ((encapsulated-fun (fdefinition name)))
249 (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
250 (profile-encapsulation-lambdas encapsulated-fun)
251 (without-package-locks
252 (setf (fdefinition name)
254 (setf (gethash name *profiled-fun-name->info*)
255 (make-profile-info :name name
256 :encapsulated-fun encapsulated-fun
257 :encapsulation-fun encapsulation-fun
258 :read-stats-fun read-stats-fun
259 :clear-stats-fun clear-stats-fun))
262 ;;; Profile the named function. If already profiled, unprofile first.
263 (defun profile-1-fun (name)
264 (cond ((fboundp name)
265 (when (gethash name *profiled-fun-name->info*)
266 (warn "~S is already profiled, so unprofiling it first." name)
267 (unprofile-1-fun name))
268 (profile-1-unprofiled-fun name))
270 (warn "ignoring undefined function ~S" name)))
273 ;;; Unprofile the named function, if it is profiled.
274 (defun unprofile-1-fun (name)
275 (let ((pinfo (gethash name *profiled-fun-name->info*)))
277 (remhash name *profiled-fun-name->info*)
278 (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
279 (without-package-locks
280 (setf (fdefinition name) (profile-info-encapsulated-fun pinfo)))
281 (warn "preserving current definition of redefined function ~S"
284 (warn "~S is not a profiled function." name))))
287 (defmacro profile (&rest names)
291 If no names are supplied, return the list of profiled functions.
293 If names are supplied, wrap profiling code around the named functions.
294 As in TRACE, the names are not evaluated. A symbol names a function.
295 A string names all the functions named by symbols in the named
296 package. If a function is already profiled, then unprofile and
297 reprofile (useful to notice function redefinition.) If a name is
298 undefined, then we give a warning and ignore it. See also
299 UNPROFILE, REPORT and RESET."
301 `(loop for k being each hash-key in *profiled-fun-name->info*
303 `(mapc-on-named-funs #'profile-1-fun ',names)))
305 (defmacro unprofile (&rest names)
307 "Unwrap any profiling code around the named functions, or if no names
308 are given, unprofile all profiled functions. A symbol names
309 a function. A string names all the functions named by symbols in the
310 named package. NAMES defaults to the list of names of all currently
313 `(mapc-on-named-funs #'unprofile-1-fun ',names)
316 (defun unprofile-all ()
317 (dohash (name profile-info *profiled-fun-name->info*)
318 (declare (ignore profile-info))
319 (unprofile-1-fun name)))
322 "Reset the counters for all profiled functions."
323 (dohash (name profile-info *profiled-fun-name->info*)
324 (declare (ignore name))
325 (funcall (profile-info-clear-stats-fun profile-info))))
327 ;;;; reporting results
329 (defstruct (time-info (:copier nil))
335 ;;; Return our best guess for the run time in a function, subtracting
336 ;;; out factors for profiling overhead. We subtract out the internal
337 ;;; overhead for each call to this function, since the internal
338 ;;; overhead is the part of the profiling overhead for a function that
339 ;;; is charged to that function.
341 ;;; We also subtract out a factor for each call to a profiled function
342 ;;; within this profiled function. This factor is the total profiling
343 ;;; overhead *minus the internal overhead*. We don't subtract out the
344 ;;; internal overhead, since it was already subtracted when the nested
345 ;;; profiled functions subtracted their running time from the time for
346 ;;; the enclosing function.
347 (defun compensate-time (calls ticks profile)
348 (let ((raw-compensated
349 (- (/ (float ticks) (float +ticks-per-second+))
350 (* (overhead-internal *overhead*) (float calls))
351 (* (- (overhead-total *overhead*)
352 (overhead-internal *overhead*))
354 (max raw-compensated 0.0)))
357 "Report results from profiling. The results are approximately adjusted
358 for profiling overhead. The compensation may be rather inaccurate when
359 bignums are involved in runtime calculation, as in a very-long-running
361 (unless (boundp '*overhead*)
364 (let ((time-info-list ())
365 (no-call-name-list ()))
366 (dohash (name pinfo *profiled-fun-name->info*)
367 (unless (eq (fdefinition name)
368 (profile-info-encapsulation-fun pinfo))
369 (warn "Function ~S has been redefined, so times may be inaccurate.~@
370 PROFILE it again to record calls to the new definition."
372 (multiple-value-bind (calls ticks consing profile)
373 (funcall (profile-info-read-stats-fun pinfo))
375 (push name no-call-name-list)
376 (push (make-time-info :name name
378 :seconds (compensate-time calls
387 :key #'time-info-seconds))
388 (print-profile-table time-info-list)
390 (when no-call-name-list
391 (format *trace-output*
392 "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
393 (sort no-call-name-list #'string<
395 (symbol-name (fun-name-block-name name))))))
400 (defun print-profile-table (time-info-list)
401 (let ((total-seconds 0.0)
404 (seconds-width (length "seconds"))
405 (consed-width (length "consed"))
406 (calls-width (length "calls"))
409 (dolist (time-info time-info-list)
410 (incf total-seconds (time-info-seconds time-info))
411 (incf total-consed (time-info-consing time-info))
412 (incf total-calls (time-info-calls time-info)))
413 (setf seconds-width (max (length (format nil "~10,3F" total-seconds))
415 calls-width (max (length (format nil "~:D" total-calls))
417 consed-width (max (length (format nil "~:D" total-consed))
421 (dotimes (i (+ seconds-width consed-width calls-width
422 sec/call-width name-width
424 (write-char #\- *trace-output*))
425 (terpri *trace-output*)))
426 (format *trace-output* "~&~@{ ~v:@<~A~>~^|~}~%"
427 seconds-width "seconds"
428 (1+ consed-width) "consed"
429 (1+ calls-width) "calls"
430 (1+ sec/call-width) "sec/call"
431 (1+ name-width) "name")
435 (dolist (time-info time-info-list)
436 (format *trace-output* "~v,3F | ~v:D | ~v:D | ~10,6F | ~S~%"
437 seconds-width (time-info-seconds time-info)
438 consed-width (time-info-consing time-info)
439 calls-width (time-info-calls time-info)
440 (/ (time-info-seconds time-info)
441 (float (time-info-calls time-info)))
442 (time-info-name time-info)))
446 (format *trace-output* "~v,3F | ~v:D | ~v:D | | Total~%"
447 seconds-width total-seconds
448 consed-width total-consed
449 calls-width total-calls)
451 (format *trace-output*
452 "~%estimated total profiling overhead: ~4,2F seconds~%"
453 (* (overhead-total *overhead*) (float total-calls)))
454 (format *trace-output*
455 "~&overhead estimation parameters:~% ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
456 (overhead-call *overhead*)
457 (overhead-total *overhead*)
458 (overhead-internal *overhead*)))))
461 ;;;; overhead estimation
463 ;;; We average the timing overhead over this many iterations.
465 ;;; (This is a variable, not a constant, so that it can be set in
466 ;;; .sbclrc if desired. Right now, that's an unsupported extension
467 ;;; that I (WHN) use for my own experimentation, but it might
468 ;;; become supported someday. Comments?)
469 (declaim (type unsigned-byte *timer-overhead-iterations*))
470 (defparameter *timer-overhead-iterations*
473 ;;; a dummy function that we profile to find profiling overhead
474 (declaim (notinline compute-overhead-aux))
475 (defun compute-overhead-aux (x)
476 (declare (ignore x)))
478 ;;; Return a newly computed OVERHEAD object.
479 (defun compute-overhead ()
480 (format *debug-io* "~&measuring PROFILE overhead..")
482 (let ((start (get-internal-ticks))
483 (fun (symbol-function 'compute-overhead-aux)))
484 (declare (type function fun))
485 (dotimes (i *timer-overhead-iterations*)
487 (/ (float (- (get-internal-ticks) start))
488 (float +ticks-per-second+)
489 (float *timer-overhead-iterations*)))))
490 (let (;; Measure unprofiled calls to estimate call overhead.
491 (call-overhead (frob))
494 ;; Measure profiled calls to estimate profiling overhead.
497 (profile compute-overhead-aux)
499 (- (frob) call-overhead)))
500 (let* ((pinfo (gethash 'compute-overhead-aux
501 *profiled-fun-name->info*))
502 (read-stats-fun (profile-info-read-stats-fun pinfo))
503 (time (nth-value 1 (funcall read-stats-fun))))
504 (setf internal-overhead
506 (float +ticks-per-second+)
507 (float *timer-overhead-iterations*))))
508 (unprofile compute-overhead-aux))
510 (make-overhead :call call-overhead
511 :total total-overhead
512 :internal internal-overhead)
513 (format *debug-io* "done~%")))))
515 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
516 ;;; then load the old *OVERHEAD* value from the .core file into a
517 ;;; different machine running at a different speed. We avoid this by
518 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
519 (defun profile-deinit ()
520 (without-package-locks
521 (makunbound '*overhead*)))