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 (setf (fdefinition name)
253 (setf (gethash name *profiled-fun-name->info*)
254 (make-profile-info :name name
255 :encapsulated-fun encapsulated-fun
256 :encapsulation-fun encapsulation-fun
257 :read-stats-fun read-stats-fun
258 :clear-stats-fun clear-stats-fun))
261 ;;; Profile the named function. If already profiled, unprofile first.
262 (defun profile-1-fun (name)
263 (cond ((fboundp name)
264 (when (gethash name *profiled-fun-name->info*)
265 (warn "~S is already profiled, so unprofiling it first." name)
266 (unprofile-1-fun name))
267 (profile-1-unprofiled-fun name))
269 (warn "ignoring undefined function ~S" name)))
272 ;;; Unprofile the named function, if it is profiled.
273 (defun unprofile-1-fun (name)
274 (let ((pinfo (gethash name *profiled-fun-name->info*)))
276 (remhash name *profiled-fun-name->info*)
277 (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
278 (setf (fdefinition name) (profile-info-encapsulated-fun pinfo))
279 (warn "preserving current definition of redefined function ~S"
282 (warn "~S is not a profiled function." name))))
285 (defmacro profile (&rest names)
289 If no names are supplied, return the list of profiled functions.
291 If names are supplied, wrap profiling code around the named functions.
292 As in TRACE, the names are not evaluated. A symbol names a function.
293 A string names all the functions named by symbols in the named
294 package. If a function is already profiled, then unprofile and
295 reprofile (useful to notice function redefinition.) If a name is
296 undefined, then we give a warning and ignore it. See also
297 UNPROFILE, REPORT and RESET."
299 `(loop for k being each hash-key in *profiled-fun-name->info*
301 `(mapc-on-named-funs #'profile-1-fun ',names)))
303 (defmacro unprofile (&rest names)
305 "Unwrap any profiling code around the named functions, or if no names
306 are given, unprofile all profiled functions. A symbol names
307 a function. A string names all the functions named by symbols in the
308 named package. NAMES defaults to the list of names of all currently
311 `(mapc-on-named-funs #'unprofile-1-fun ',names)
314 (defun unprofile-all ()
315 (dohash (name profile-info *profiled-fun-name->info*)
316 (declare (ignore profile-info))
317 (unprofile-1-fun name)))
320 "Reset the counters for all profiled functions."
321 (dohash (name profile-info *profiled-fun-name->info*)
322 (declare (ignore name))
323 (funcall (profile-info-clear-stats-fun profile-info))))
325 ;;;; reporting results
327 (defstruct (time-info (:copier nil))
333 ;;; Return our best guess for the run time in a function, subtracting
334 ;;; out factors for profiling overhead. We subtract out the internal
335 ;;; overhead for each call to this function, since the internal
336 ;;; overhead is the part of the profiling overhead for a function that
337 ;;; is charged to that function.
339 ;;; We also subtract out a factor for each call to a profiled function
340 ;;; within this profiled function. This factor is the total profiling
341 ;;; overhead *minus the internal overhead*. We don't subtract out the
342 ;;; internal overhead, since it was already subtracted when the nested
343 ;;; profiled functions subtracted their running time from the time for
344 ;;; the enclosing function.
345 (defun compensate-time (calls ticks profile)
346 (let ((raw-compensated
347 (- (/ (float ticks) (float +ticks-per-second+))
348 (* (overhead-internal *overhead*) (float calls))
349 (* (- (overhead-total *overhead*)
350 (overhead-internal *overhead*))
352 (max raw-compensated 0.0)))
355 "Report results from profiling. The results are approximately adjusted
356 for profiling overhead. The compensation may be rather inaccurate when
357 bignums are involved in runtime calculation, as in a very-long-running
359 (unless (boundp '*overhead*)
362 (let ((time-info-list ())
363 (no-call-name-list ()))
364 (dohash (name pinfo *profiled-fun-name->info*)
365 (unless (eq (fdefinition name)
366 (profile-info-encapsulation-fun pinfo))
367 (warn "Function ~S has been redefined, so times may be inaccurate.~@
368 PROFILE it again to record calls to the new definition."
370 (multiple-value-bind (calls ticks consing profile)
371 (funcall (profile-info-read-stats-fun pinfo))
373 (push name no-call-name-list)
374 (push (make-time-info :name name
376 :seconds (compensate-time calls
385 :key #'time-info-seconds))
387 (format *trace-output*
388 "~& seconds | consed | calls | sec/call | name~@
389 ------------------------------------------------------~%")
391 (let ((total-time 0.0)
394 (dolist (time-info time-info-list)
395 (incf total-time (time-info-seconds time-info))
396 (incf total-calls (time-info-calls time-info))
397 (incf total-consed (time-info-consing time-info))
398 (format *trace-output*
399 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
400 (time-info-seconds time-info)
401 (time-info-consing time-info)
402 (time-info-calls time-info)
403 (/ (time-info-seconds time-info)
404 (float (time-info-calls time-info)))
405 (time-info-name time-info)))
406 (format *trace-output*
407 "------------------------------------------------------~@
408 ~10,3F | ~9:D | ~7:D | | Total~%"
409 total-time total-consed total-calls)
410 (format *trace-output*
411 "~%estimated total profiling overhead: ~4,2F seconds~%"
412 (* (overhead-total *overhead*) (float total-calls)))
413 (format *trace-output*
414 "~&overhead estimation parameters:~% ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
415 (overhead-call *overhead*)
416 (overhead-total *overhead*)
417 (overhead-internal *overhead*)))
419 (when no-call-name-list
420 (format *trace-output*
421 "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
422 (sort no-call-name-list #'string<
424 (symbol-name (fun-name-block-name name))))))
428 ;;;; overhead estimation
430 ;;; We average the timing overhead over this many iterations.
432 ;;; (This is a variable, not a constant, so that it can be set in
433 ;;; .sbclrc if desired. Right now, that's an unsupported extension
434 ;;; that I (WHN) use for my own experimentation, but it might
435 ;;; become supported someday. Comments?)
436 (declaim (type unsigned-byte *timer-overhead-iterations*))
437 (defparameter *timer-overhead-iterations*
440 ;;; a dummy function that we profile to find profiling overhead
441 (declaim (notinline compute-overhead-aux))
442 (defun compute-overhead-aux (x)
443 (declare (ignore x)))
445 ;;; Return a newly computed OVERHEAD object.
446 (defun compute-overhead ()
447 (format *debug-io* "~&measuring PROFILE overhead..")
449 (let ((start (get-internal-ticks))
450 (fun (symbol-function 'compute-overhead-aux)))
451 (declare (type function fun))
452 (dotimes (i *timer-overhead-iterations*)
454 (/ (float (- (get-internal-ticks) start))
455 (float +ticks-per-second+)
456 (float *timer-overhead-iterations*)))))
457 (let (;; Measure unprofiled calls to estimate call overhead.
458 (call-overhead (frob))
461 ;; Measure profiled calls to estimate profiling overhead.
464 (profile compute-overhead-aux)
466 (- (frob) call-overhead)))
467 (let* ((pinfo (gethash 'compute-overhead-aux
468 *profiled-fun-name->info*))
469 (read-stats-fun (profile-info-read-stats-fun pinfo))
470 (time (nth-value 1 (funcall read-stats-fun))))
471 (setf internal-overhead
473 (float +ticks-per-second+)
474 (float *timer-overhead-iterations*))))
475 (unprofile compute-overhead-aux))
477 (make-overhead :call call-overhead
478 :total total-overhead
479 :internal internal-overhead)
480 (format *debug-io* "done~%")))))
482 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
483 ;;; then load the old *OVERHEAD* value from the .core file into a
484 ;;; different machine running at a different speed. We avoid this by
485 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
487 (makunbound '*overhead*))
488 *before-save-initializations*)