1 ;;; Copyright (C) 2003 Gerd Moellmann <gerd.moellmann@t-online.de>
2 ;;; All rights reserved.
4 ;;; Redistribution and use in source and binary forms, with or without
5 ;;; modification, are permitted provided that the following conditions
8 ;;; 1. Redistributions of source code must retain the above copyright
9 ;;; notice, this list of conditions and the following disclaimer.
10 ;;; 2. Redistributions in binary form must reproduce the above copyright
11 ;;; notice, this list of conditions and the following disclaimer in the
12 ;;; documentation and/or other materials provided with the distribution.
13 ;;; 3. The name of the author may not be used to endorse or promote
14 ;;; products derived from this software without specific prior written
17 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
18 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
21 ;;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
23 ;;; OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 ;;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 ;;; USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
30 ;;; Statistical profiler.
34 ;;; This profiler arranges for SIGPROF interrupts to interrupt a
35 ;;; running program at regular intervals. Each time a SIGPROF occurs,
36 ;;; the current program counter and return address is recorded in a
37 ;;; vector, until a configurable maximum number of samples have been
40 ;;; A profiling report is generated from the samples array by
41 ;;; determining the Lisp functions corresponding to the recorded
42 ;;; addresses. Each program counter/return address pair forms one
43 ;;; edge in a call graph.
47 ;;; The code being generated on x86 makes determining callers reliably
48 ;;; something between extremely difficult and impossible. Example:
50 ;;; 10979F00: .entry eval::eval-stack-args(arg-count)
51 ;;; 18: pop dword ptr [ebp-8]
52 ;;; 1B: lea esp, [ebp-32]
57 ;;; 29: mov [ebp-12], edi
58 ;;; 2C: mov dword ptr [ebp-16], #x28F0000B ; nil
59 ;;; ; No-arg-parsing entry point
60 ;;; 33: mov dword ptr [ebp-20], 0
62 ;;; 3C: L0: mov edx, esp
64 ;;; 41: mov eax, [#x10979EF8] ; #<FDEFINITION object for eval::eval-stack-pop>
66 ;;; 49: mov [edx-4], ebp
68 ;;; 4E: call dword ptr [eax+5]
71 ;;; Suppose this function is interrupted by SIGPROF at 4E. At that
72 ;;; point, the frame pointer EBP has been modified so that the
73 ;;; original return address of the caller of eval-stack-args is no
74 ;;; longer where it can be found by x86-call-context, and the new
75 ;;; return address, for the call to eval-stack-pop, is not yet on the
76 ;;; stack. The effect is that x86-call-context returns something
77 ;;; bogus, which leads to wrong edges in the call graph.
79 ;;; One thing that one might try is filtering cases where the program
80 ;;; is interrupted at a call instruction. But since the above example
81 ;;; of an interrupt at a call instruction isn't the only case where
82 ;;; the stack is something x86-call-context can't really cope with,
83 ;;; this is not a general solution.
85 ;;; Random ideas for implementation:
87 ;;; * Space profiler. Sample when new pages are allocated instead of
90 ;;; * Record a configurable number of callers up the stack. That
91 ;;; could give a more complete graph when there are many small
94 ;;; * Print help strings for reports, include hints to the problem
97 ;;; * Make flat report the default since call-graph isn't that
100 (defpackage #:sb-sprof
101 (:use
#:cl
#:sb-ext
#:sb-unix
#:sb-alien
#:sb-sys
)
102 (:export
#:*sample-interval
* #:*max-samples
* #:*alloc-interval
*
103 #:*report-sort-by
* #:*report-sort-order
*
104 #:start-sampling
#:stop-sampling
#:with-sampling
105 #:with-profiling
#:start-profiling
#:stop-profiling
106 #:profile-call-counts
#:unprofile-call-counts
109 (in-package #:sb-sprof
)
114 (defstruct (vertex (:constructor make-vertex
)
115 (:constructor make-scc
(scc-vertices edges
)))
116 (visited nil
:type boolean
)
117 (root nil
:type
(or null vertex
))
119 (edges () :type list
)
120 (scc-vertices () :type list
))
123 (vertex (sb-impl::missing-arg
) :type vertex
))
126 (vertices () :type list
))
128 (declaim (inline scc-p
))
129 (defun scc-p (vertex)
130 (not (null (vertex-scc-vertices vertex
))))
132 (defmacro do-vertices
((vertex graph
) &body body
)
133 `(dolist (,vertex
(graph-vertices ,graph
))
136 (defmacro do-edges
((edge edge-to vertex
) &body body
)
137 `(dolist (,edge
(vertex-edges ,vertex
))
138 (let ((,edge-to
(edge-vertex ,edge
)))
141 (defun self-cycle-p (vertex)
142 (do-edges (e to vertex
)
146 (defun map-vertices (fn vertices
)
148 (setf (vertex-visited v
) nil
))
150 (unless (vertex-visited v
)
153 ;;; Eeko Nuutila, Eljas Soisalon-Soininen, around 1992. Improves on
154 ;;; Tarjan's original algorithm by not using the stack when processing
155 ;;; trivial components. Trivial components should appear frequently
156 ;;; in a call-graph such as ours, I think. Same complexity O(V+E) as
158 (defun strong-components (vertices)
159 (let ((in-component (make-array (length vertices
)
160 :element-type
'boolean
161 :initial-element nil
))
165 (labels ((min-root (x y
)
166 (let ((rx (vertex-root x
))
167 (ry (vertex-root y
)))
168 (if (< (vertex-dfn rx
) (vertex-dfn ry
))
172 (aref in-component
(vertex-dfn v
)))
173 ((setf in-component
) (in v
)
174 (setf (aref in-component
(vertex-dfn v
)) in
))
176 (> (vertex-dfn x
) (vertex-dfn y
)))
178 (setf (vertex-dfn v
) (incf dfn
)
181 (vertex-visited v
) t
)
183 (unless (vertex-visited w
)
185 (unless (in-component w
)
186 (setf (vertex-root v
) (min-root v w
))))
187 (if (eq v
(vertex-root v
))
188 (loop while
(and stack
(vertex-> (car stack
) v
))
190 collect w into this-component
191 do
(setf (in-component w
) t
)
193 (setf (in-component v
) t
)
194 (push (cons v this-component
) components
))
196 (map-vertices #'visit vertices
)
199 ;;; Given a dag as a list of vertices, return the list sorted
200 ;;; topologically, children first.
201 (defun topological-sort (dag)
204 (labels ((rec-sort (v)
205 (setf (vertex-visited v
) t
)
206 (setf (vertex-dfn v
) (incf dfn
))
207 (dolist (e (vertex-edges v
))
208 (unless (vertex-visited (edge-vertex e
))
209 (rec-sort (edge-vertex e
))))
211 (map-vertices #'rec-sort dag
)
214 ;;; Reduce graph G to a dag by coalescing strongly connected components
215 ;;; into vertices. Sort the result topologically.
216 (defun reduce-graph (graph &optional
(scc-constructor #'make-scc
))
217 (sb-int:collect
((sccs) (trivial))
218 (dolist (c (strong-components (graph-vertices graph
)))
219 (if (or (cdr c
) (self-cycle-p (car c
)))
220 (sb-int:collect
((outgoing))
225 (sccs (funcall scc-constructor c
(outgoing))))
228 (dolist (v (trivial))
230 (when (member w
(vertex-scc-vertices scc
))
231 (setf (edge-vertex e
) scc
)))))
232 (setf (graph-vertices graph
)
233 (topological-sort (nconc (sccs) (trivial))))))
238 "Type used for addresses, for instance, program counters,
239 code start/end locations etc."
240 '(unsigned-byte #.sb-vm
::n-machine-word-bits
))
242 (defconstant +unknown-address
+ 0
243 "Constant representing an address that cannot be determined.")
245 ;;; A call graph. Vertices are NODE structures, edges are CALL
247 (defstruct (call-graph (:include graph
)
248 (:constructor %make-call-graph
))
249 ;; the value of *SAMPLE-INTERVAL* or *ALLOC-INTERVAL* at the time
250 ;; the graph was created (depending on the current allocation mode)
251 (sample-interval (sb-impl::missing-arg
) :type number
)
252 ;; the sampling-mode that was used for the profiling run
253 (sampling-mode (sb-impl::missing-arg
) :type
(member :cpu
:alloc
:time
))
254 ;; number of samples taken
255 (nsamples (sb-impl::missing-arg
) :type sb-int
:index
)
256 ;; threads that have been sampled
257 (sampled-threads nil
:type list
)
258 ;; sample count for samples not in any function
259 (elsewhere-count (sb-impl::missing-arg
) :type sb-int
:index
)
260 ;; a flat list of NODEs, sorted by sample count
261 (flat-nodes () :type list
))
263 ;;; A node in a call graph, representing a function that has been
264 ;;; sampled. The edges of a node are CALL structures that represent
265 ;;; functions called from a given node.
266 (defstruct (node (:include vertex
)
267 (:constructor %make-node
))
268 ;; A numeric label for the node. The most frequently called function
269 ;; gets label 1. This is just for identification purposes in the
271 (index 0 :type fixnum
)
272 ;; Start and end address of the function's code. Depending on the
273 ;; debug-info, this might be either as absolute addresses for things
274 ;; that won't move around in memory, or as relative offsets from
275 ;; some point for things that might move.
276 (start-pc-or-offset 0 :type address
)
277 (end-pc-or-offset 0 :type address
)
278 ;; the name of the function
280 ;; sample count for this function
281 (count 0 :type fixnum
)
282 ;; count including time spent in functions called from this one
283 (accrued-count 0 :type fixnum
)
284 ;; the debug-info that this node was created from
285 (debug-info nil
:type t
)
286 ;; list of NODEs for functions calling this one
287 (callers () :type list
)
288 ;; the call count for the function that corresponds to this node (or NIL
289 ;; if call counting wasn't enabled for this function)
290 (call-count nil
:type
(or null integer
)))
292 ;;; A cycle in a call graph. The functions forming the cycle are
293 ;;; found in the SCC-VERTICES slot of the VERTEX structure.
294 (defstruct (cycle (:include node
)))
296 ;;; An edge in a call graph. EDGE-VERTEX is the function being
298 (defstruct (call (:include edge
)
299 (:constructor make-call
(vertex)))
300 ;; number of times the call was sampled
301 (count 1 :type sb-int
:index
))
303 (defvar *sample-interval
* 0.01
304 "Default number of seconds between samples.")
305 (declaim (type number
*sample-interval
*))
307 (defvar *alloc-interval
* 4
308 "Default number of allocation region openings between samples.")
309 (declaim (type number
*alloc-interval
*))
311 (defvar *max-samples
* 50000
312 "Default number of traces taken. This variable is somewhat misnamed:
313 each trace may actually consist of an arbitrary number of samples, depending
314 on the depth of the call stack.")
315 (declaim (type sb-int
:index
*max-samples
*))
317 ;;; Encapsulate all the information about a sampling run
319 ;; When this vector fills up, we allocate a new one and copy over
321 (vector (make-array (* *max-samples
*
322 ;; Arbitrary guess at how many samples we'll be
323 ;; taking for each trace. The exact amount doesn't
324 ;; matter, this is just to decrease the amount of
325 ;; re-allocation that will need to be done.
327 ;; Each sample takes two cells in the vector
330 (trace-count 0 :type sb-int
:index
)
331 (index 0 :type sb-int
:index
)
332 (mode nil
:type
(member :cpu
:alloc
:time
))
333 (sample-interval (sb-int:missing-arg
) :type number
)
334 (alloc-interval (sb-int:missing-arg
) :type number
)
335 (max-depth most-positive-fixnum
:type number
)
336 (max-samples (sb-int:missing-arg
) :type sb-int
:index
)
337 (sampled-threads nil
:type list
))
339 (defmethod print-object ((call-graph call-graph
) stream
)
340 (print-unreadable-object (call-graph stream
:type t
:identity t
)
341 (format stream
"~d samples" (call-graph-nsamples call-graph
))))
343 (defmethod print-object ((node node
) stream
)
344 (print-unreadable-object (node stream
:type t
:identity t
)
345 (format stream
"~s [~d]" (node-name node
) (node-index node
))))
347 (defmethod print-object ((call call
) stream
)
348 (print-unreadable-object (call stream
:type t
:identity t
)
349 (format stream
"~s [~d]" (node-name (call-vertex call
))
350 (node-index (call-vertex call
)))))
352 (deftype report-type
()
353 '(member nil
:flat
:graph
))
355 (defvar *sampling-mode
* :cpu
356 "Default sampling mode. :CPU for cpu profiling, :ALLOC for allocation
358 (declaim (type (member :cpu
:alloc
:time
) *sampling-mode
*))
360 (defvar *alloc-region-size
*
363 ;; This hardcoded 2 matches the one in gc_find_freeish_pages. It's not
364 ;; really worth genesifying.
366 (* 2 sb-vm
:gencgc-page-bytes
))
367 (declaim (type number
*alloc-region-size
*))
369 (defvar *samples
* nil
)
370 (declaim (type (or null samples
) *samples
*))
372 (defvar *profiling
* nil
)
373 (declaim (type (member nil
:alloc
:cpu
:time
) *profiling
*))
374 (defvar *sampling
* nil
)
375 (declaim (type boolean
*sampling
*))
377 (defvar *show-progress
* nil
)
379 (defvar *old-sampling
* nil
)
381 ;; Call count encapsulation information
382 (defvar *encapsulations
* (make-hash-table :test
'equal
))
384 (defun turn-off-sampling ()
385 (setq *old-sampling
* *sampling
*)
386 (setq *sampling
* nil
))
388 (defun turn-on-sampling ()
389 (setq *sampling
* *old-sampling
*))
391 (defun show-progress (format-string &rest args
)
392 (when *show-progress
*
393 (apply #'format t format-string args
)
396 (defun start-sampling ()
397 "Switch on statistical sampling."
400 (defun stop-sampling ()
401 "Switch off statistical sampling."
402 (setq *sampling
* nil
))
404 (defmacro with-sampling
((&optional
(on t
)) &body body
)
405 "Evaluate body with statistical sampling turned on or off."
406 `(let ((*sampling
* ,on
)
407 (sb-vm:*alloc-signal
* sb-vm
:*alloc-signal
*))
410 ;;; Return something serving as debug info for address PC.
411 (declaim (inline debug-info
))
412 (defun debug-info (pc)
413 (declare (type system-area-pointer pc
)
414 (muffle-conditions compiler-note
))
415 (let ((ptr (sb-di::component-ptr-from-pc pc
)))
416 (cond ((sap= ptr
(int-sap 0))
417 (let ((name (sap-foreign-symbol pc
)))
419 (values (format nil
"foreign function ~a" name
)
421 (values nil
(sap-int pc
)))))
423 (let* ((code (sb-di::component-from-component-ptr ptr
))
424 (code-header-len (* (sb-kernel:get-header-data code
)
426 (pc-offset (- (sap-int pc
)
427 (- (sb-kernel:get-lisp-obj-address code
)
428 sb-vm
:other-pointer-lowtag
)
430 (df (sb-di::debug-fun-from-pc code pc-offset
)))
431 (cond ((typep df
'sb-di
::bogus-debug-fun
)
432 (values code
(sap-int pc
)))
434 ;; The code component might be moved by the GC. Store
435 ;; a PC offset, and reconstruct the data in
436 ;; SAMPLE-PC-FROM-PC-OR-OFFSET.
437 (values df pc-offset
))
439 (values nil
0))))))))
441 (defun ensure-samples-vector (samples)
442 (let ((vector (samples-vector samples
))
443 (index (samples-index samples
)))
444 ;; Allocate a new sample vector if the old one is full
445 (if (= (length vector
) index
)
446 (let ((new-vector (make-array (* 2 index
))))
447 (format *trace-output
* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
448 (samples-trace-count samples
)
450 (replace new-vector vector
)
451 (setf (samples-vector samples
) new-vector
))
454 (declaim (inline record
))
455 (defun record (samples pc
)
456 (declare (type system-area-pointer pc
)
457 (muffle-conditions compiler-note
))
458 (multiple-value-bind (info pc-or-offset
)
460 (let ((vector (ensure-samples-vector samples
))
461 (index (samples-index samples
)))
462 (declare (type simple-vector vector
))
463 ;; Allocate a new sample vector if the old one is full
464 (when (= (length vector
) index
)
465 (let ((new-vector (make-array (* 2 index
))))
466 (format *trace-output
* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
467 (samples-trace-count samples
)
469 (replace new-vector vector
)
470 (setf vector new-vector
471 (samples-vector samples
) new-vector
)))
472 ;; For each sample, store the debug-info and the PC/offset into
474 (setf (aref vector index
) info
475 (aref vector
(1+ index
)) pc-or-offset
)))
476 (incf (samples-index samples
) 2))
478 (defun record-trace-start (samples)
479 ;; Mark the start of the trace.
480 (let ((vector (ensure-samples-vector samples
)))
481 (declare (type simple-vector vector
))
482 (setf (aref vector
(samples-index samples
))
484 (incf (samples-index samples
) 2))
486 ;;; List of thread currently profiled, or :ALL for all threads.
487 (defvar *profiled-threads
* nil
)
488 (declaim (type (or list
(member :all
)) *profiled-threads
*))
490 ;;; Thread which runs the wallclock timers, if any.
491 (defvar *timer-thread
* nil
)
493 (defun profiled-threads ()
494 (let ((profiled-threads *profiled-threads
*))
495 (if (eq :all profiled-threads
)
496 (remove *timer-thread
* (sb-thread:list-all-threads
))
499 (defun profiled-thread-p (thread)
500 (let ((profiled-threads *profiled-threads
*))
501 (or (and (eq :all profiled-threads
)
502 (not (eq *timer-thread
* thread
)))
503 (member thread profiled-threads
:test
#'eq
))))
507 ;; Ensure that only one thread at a time will be doing profiling stuff.
508 (defvar *profiler-lock
* (sb-thread:make-mutex
:name
"Statistical Profiler"))
509 (defvar *distribution-lock
* (sb-thread:make-mutex
:name
"Wallclock profiling lock"))
511 (define-alien-routine pthread-kill int
(signal int
) (os-thread unsigned-long
))
513 ;;; A random thread will call this in response to either a timer firing,
514 ;;; This in turn will distribute the notice to those threads we are
515 ;;; interested using SIGPROF.
516 (defun thread-distribution-handler ()
517 (declare (optimize sb-c
::merge-tail-calls
))
520 (let ((lock *distribution-lock
*))
521 ;; Don't flood the system with more interrupts if the last
522 ;; set is still being delivered.
523 (unless (sb-thread:mutex-value lock
)
524 (sb-thread::with-system-mutex
(lock)
525 (dolist (thread (profiled-threads))
526 ;; This may occasionally fail to deliver the signal, but that
527 ;; seems better then using kill_thread_safely with it's 1
529 (let ((os-thread (sb-thread::thread-os-thread thread
)))
531 (pthread-kill os-thread sb-unix
:sigprof
)))))))
533 (unix-kill 0 sb-unix
:sigprof
)))
535 (defun sigprof-handler (signal code scp
)
536 (declare (ignore signal code
) (optimize speed
(space 0))
537 (disable-package-locks sb-di
::x86-call-context
)
538 (muffle-conditions compiler-note
)
539 (type system-area-pointer scp
))
540 (let ((self sb-thread
:*current-thread
*)
541 (profiling *profiling
*))
542 ;; Turn off allocation counter when it is not needed. Doing this in the
543 ;; signal handler means we don't have to worry about racing with the runtime
544 (unless (eq :alloc profiling
)
545 (setf sb-vm
::*alloc-signal
* nil
))
546 (when (and *sampling
*
547 ;; Normal SIGPROF gets practically speaking delivered to threads
548 ;; depending on the run time they use, so we need to filter
549 ;; out those we don't care about. For :ALLOC and :TIME profiling
550 ;; only the interesting threads get SIGPROF in the first place.
552 ;; ...except that Darwin at least doesn't seem to work like we
553 ;; would want it to, which makes multithreaded :CPU profiling pretty
554 ;; pointless there -- though it may be that our mach magic is
555 ;; partially to blame?
556 (or (not (eq :cpu profiling
)) (profiled-thread-p self
)))
557 (sb-thread::with-system-mutex
(*profiler-lock
* :without-gcing t
)
558 (let ((samples *samples
*))
560 (< (samples-trace-count samples
)
561 (samples-max-samples samples
)))
562 (with-alien ((scp (* os-context-t
) :local scp
))
563 (let* ((pc-ptr (sb-vm:context-pc scp
))
564 (fp (sb-vm::context-register scp
#.sb-vm
::ebp-offset
)))
565 ;; foreign code might not have a useful frame
566 ;; pointer in ebp/rbp, so make sure it looks
567 ;; reasonable before walking the stack
568 (unless (sb-di::control-stack-pointer-valid-p
(sb-sys:int-sap fp
))
569 (record samples pc-ptr
)
570 (return-from sigprof-handler nil
))
571 (incf (samples-trace-count samples
))
572 (pushnew self
(samples-sampled-threads samples
))
573 (let ((fp (int-sap fp
))
575 (declare (type system-area-pointer fp pc-ptr
))
576 ;; FIXME: How annoying. The XC doesn't store enough
577 ;; type information about SB-DI::X86-CALL-CONTEXT,
578 ;; even if we declaim the ftype explicitly in
579 ;; src/code/debug-int. And for some reason that type
580 ;; information is needed for the inlined version to
581 ;; be compiled without boxing the returned saps. So
582 ;; we declare the correct ftype here manually, even
583 ;; if the compiler should be able to deduce this
584 ;; exact same information.
585 (declare (ftype (function (system-area-pointer)
586 (values (member nil t
)
588 system-area-pointer
))
589 sb-di
::x86-call-context
))
590 (record-trace-start samples
)
591 (dotimes (i (samples-max-depth samples
))
592 (record samples pc-ptr
)
593 (setf (values ok pc-ptr fp
)
594 (sb-di::x86-call-context fp
))
597 ;; Reset thread-local allocation counter before interrupts
599 (when (eq t sb-vm
::*alloc-signal
*)
600 (setf sb-vm
:*alloc-signal
* (1- (samples-alloc-interval samples
)))))))))
603 ;; FIXME: On non-x86 platforms we don't yet walk the call stack deeper
606 (defun sigprof-handler (signal code scp
)
607 (declare (ignore signal code
))
608 (sb-sys:without-interrupts
609 (let ((samples *samples
*))
610 (when (and *sampling
*
612 (< (samples-trace-count samples
)
613 (samples-max-samples samples
)))
614 (sb-sys:without-gcing
615 (with-alien ((scp (* os-context-t
) :local scp
))
616 (locally (declare (optimize (inhibit-warnings 2)))
617 (incf (samples-trace-count samples
))
618 (record-trace-start samples
)
619 (let* ((pc-ptr (sb-vm:context-pc scp
))
620 (fp (sb-vm::context-register scp
#.sb-vm
::cfp-offset
))
623 (* sb-vm
::lra-save-offset sb-vm
::n-word-bytes
))))
624 (record samples pc-ptr
)
625 (record samples
(int-sap ra
))))))))))
627 ;;; Return the start address of CODE.
628 (defun code-start (code)
629 (declare (type sb-kernel
:code-component code
))
630 (sap-int (sb-kernel:code-instructions code
)))
632 ;;; Return start and end address of CODE as multiple values.
633 (defun code-bounds (code)
634 (declare (type sb-kernel
:code-component code
))
635 (let* ((start (code-start code
))
636 (end (+ start
(sb-kernel:%code-code-size code
))))
639 (defmacro with-profiling
((&key
(sample-interval '*sample-interval
*)
640 (alloc-interval '*alloc-interval
*)
641 (max-samples '*max-samples
*)
643 (mode '*sampling-mode
*)
645 (max-depth most-positive-fixnum
)
647 (threads '(list sb-thread
:*current-thread
*))
648 (report nil report-p
))
650 "Repeatedly evaluate BODY with statistical profiling turned on.
651 In multi-threaded operation, only the thread in which WITH-PROFILING
652 was evaluated will be profiled by default. If you want to profile
653 multiple threads, invoke the profiler with START-PROFILING.
655 The following keyword args are recognized:
658 Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
661 Take a sample every time <n> allocation regions (approximately
662 8kB) have been allocated since the last sample. Default is
666 If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run the
667 profiler in allocation profiling mode. If :TIME, run the profiler
668 in wallclock profiling mode.
671 Repeat evaluating body until <max> samples are taken.
672 Default is *MAX-SAMPLES*.
675 Maximum call stack depth that the profiler should consider. Only
676 has an effect on x86 and x86-64.
679 If specified, call REPORT with :TYPE <type> at the end.
682 It true, call RESET at the beginning.
685 Form that evaluates to the list threads to profile, or :ALL to indicate
686 that all threads should be profiled. Defaults to the current
687 thread. (Note: START-PROFILING defaults to all threads.)
689 :THREADS has no effect on call-counting at the moment.
691 On some platforms (eg. Darwin) the signals used by the profiler are
692 not properly delivered to threads in proportion to their CPU usage
693 when doing :CPU profiling. If you see empty call graphs, or are obviously
694 missing several samples from certain threads, you may be falling afoul
698 If true (the default) repeatedly evaluate BODY. If false, evaluate
700 (declare (type report-type report
))
701 `(let* ((*sample-interval
* ,sample-interval
)
702 (*alloc-interval
* ,alloc-interval
)
704 (*sampling-mode
* ,mode
)
705 (*max-samples
* ,max-samples
))
706 ,@(when reset
'((reset)))
709 (start-profiling :max-depth
,max-depth
:threads
,threads
)
711 (when (>= (samples-trace-count *samples
*)
712 (samples-max-samples *samples
*))
714 ,@(when show-progress
715 `((format t
"~&===> ~d of ~d samples taken.~%"
716 (samples-trace-count *samples
*)
717 (samples-max-samples *samples
*))))
718 (let ((.last-index.
(samples-index *samples
*)))
720 (when (= .last-index.
(samples-index *samples
*))
721 (warn "No sampling progress; possibly a profiler bug.")
726 ,@(when report-p
`((report :type
,report
)))))
730 (defvar *old-alloc-interval
* nil
)
731 (defvar *old-sample-interval
* nil
)
733 (defun start-profiling (&key
(max-samples *max-samples
*)
734 (mode *sampling-mode
*)
735 (sample-interval *sample-interval
*)
736 (alloc-interval *alloc-interval
*)
737 (max-depth most-positive-fixnum
)
740 "Start profiling statistically in the current thread if not already profiling.
741 The following keyword args are recognized:
744 Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
747 Take a sample every time <n> allocation regions (approximately
748 8kB) have been allocated since the last sample. Default is
752 If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run
753 the profiler in allocation profiling mode. If :TIME, run the profiler
754 in wallclock profiling mode.
757 Maximum number of samples. Default is *MAX-SAMPLES*.
760 Maximum call stack depth that the profiler should consider. Only
761 has an effect on x86 and x86-64.
764 List threads to profile, or :ALL to indicate that all threads should be
765 profiled. Defaults to :ALL. (Note: WITH-PROFILING defaults to the current
768 :THREADS has no effect on call-counting at the moment.
770 On some platforms (eg. Darwin) the signals used by the profiler are
771 not properly delivered to threads in proportion to their CPU usage
772 when doing :CPU profiling. If you see empty call graphs, or are obviously
773 missing several samples from certain threads, you may be falling afoul
777 If true, the default, start sampling right away.
778 If false, START-SAMPLING can be used to turn sampling on."
780 (when (eq mode
:alloc
)
781 (error "Allocation profiling is only supported for builds using the generational garbage collector."))
783 (multiple-value-bind (secs usecs
)
784 (multiple-value-bind (secs rest
)
785 (truncate sample-interval
)
786 (values secs
(truncate (* rest
1000000))))
787 (setf *sampling
* sampling
788 *samples
* (make-samples :max-depth max-depth
789 :max-samples max-samples
790 :sample-interval sample-interval
791 :alloc-interval alloc-interval
793 (enable-call-counting)
794 (setf *profiled-threads
* threads
)
795 (sb-sys:enable-interrupt sb-unix
:sigprof
#'sigprof-handler
)
798 (let ((alloc-signal (1- alloc-interval
)))
801 (when (eq :all threads
)
802 ;; Set the value new threads inherit.
803 (sb-thread::with-all-threads-lock
804 (setf sb-thread
::*default-alloc-signal
* alloc-signal
)))
805 ;; Turn on allocation profiling in existing threads.
806 (dolist (thread (profiled-threads))
807 (sb-thread::%set-symbol-value-in-thread
'sb-vm
::*alloc-signal
* thread alloc-signal
)))
809 (setf sb-vm
:*alloc-signal
* alloc-signal
)))
811 (unix-setitimer :profile secs usecs secs usecs
))
814 (let ((setup (sb-thread:make-semaphore
:name
"Timer thread setup semaphore")))
816 (sb-thread:make-thread
(lambda ()
817 (sb-thread:wait-on-semaphore setup
)
818 (loop while
(eq sb-thread
:*current-thread
* *timer-thread
*)
820 :name
"SB-SPROF wallclock timer thread"))
821 (sb-thread:signal-semaphore setup
))
823 (setf *timer-thread
* nil
)
824 (setf *timer
* (make-timer #'thread-distribution-handler
:name
"SB-PROF wallclock timer"
825 :thread
*timer-thread
*))
826 (schedule-timer *timer
* sample-interval
:repeat-interval sample-interval
)))
827 (setq *profiling
* mode
)))
830 (defun stop-profiling ()
831 "Stop profiling if profiling."
832 (let ((profiling *profiling
*))
834 ;; Even with the timers shut down we cannot be sure that there is no
835 ;; undelivered sigprof. The handler is also responsible for turning the
836 ;; *ALLOC-SIGNAL* off in individual threads.
840 (setf sb-thread
::*default-alloc-signal
* nil
)
842 (setf sb-vm
:*alloc-signal
* nil
))
844 (unix-setitimer :profile
0 0 0 0))
846 (unschedule-timer *timer
*)
848 *timer-thread
* nil
)))
849 (disable-call-counting)
850 (setf *profiling
* nil
852 *profiled-threads
* nil
)))
856 "Reset the profiler."
858 (setq *sampling
* nil
)
862 ;;; Make a NODE for debug-info INFO.
863 (defun make-node (info)
864 (flet ((clean-name (name)
865 (if (and (consp name
)
867 '(sb-c::xep sb-c
::tl-xep sb-c
::&more-processor
870 sb-c
::hairy-arg-processor
871 sb-c
::&optional-processor
)))
875 (sb-kernel::code-component
876 (multiple-value-bind (start end
)
879 (%make-node
:name
(or (sb-disassem::find-assembler-routine start
)
880 (format nil
"~a" info
))
882 :start-pc-or-offset start
883 :end-pc-or-offset end
)
885 (sb-di::compiled-debug-fun
886 (let* ((name (sb-di::debug-fun-name info
))
887 (cdf (sb-di::compiled-debug-fun-compiler-debug-fun info
))
888 (start-offset (sb-c::compiled-debug-fun-start-pc cdf
))
889 (end-offset (sb-c::compiled-debug-fun-elsewhere-pc cdf
))
890 (component (sb-di::compiled-debug-fun-component info
))
891 (start-pc (code-start component
)))
892 ;; Call graphs are mostly useless unless we somehow
893 ;; distinguish a gazillion different (LAMBDA ())'s.
894 (when (equal name
'(lambda ()))
895 (setf name
(format nil
"Unknown component: #x~x" start-pc
)))
896 (values (%make-node
:name
(clean-name name
)
898 :start-pc-or-offset start-offset
899 :end-pc-or-offset end-offset
)
902 (%make-node
:name
(clean-name (sb-di::debug-fun-name info
))
905 (%make-node
:name
(coerce info
'string
)
906 :debug-info info
)))))
908 ;;; One function can have more than one COMPILED-DEBUG-FUNCTION with
909 ;;; the same name. Reduce the number of calls to Debug-Info by first
910 ;;; looking for a given PC in a red-black tree. If not found in the
911 ;;; tree, get debug info, and look for a node in a hash-table by
912 ;;; function name. If not found in the hash-table, make a new node.
914 (defvar *name-
>node
*)
916 (defmacro with-lookup-tables
(() &body body
)
917 `(let ((*name-
>node
* (make-hash-table :test
'equal
)))
920 ;;; Find or make a new node for INFO. Value is the NODE found or
921 ;;; made; NIL if not enough information exists to make a NODE for INFO.
922 (defun lookup-node (info)
924 (multiple-value-bind (new key
)
926 (when (eql (node-name new
) 'call-counter
)
927 (return-from lookup-node
(values nil nil
)))
928 (let* ((key (cons (node-name new
) key
))
929 (found (gethash key
*name-
>node
*)))
931 (setf (node-start-pc-or-offset found
)
932 (min (node-start-pc-or-offset found
)
933 (node-start-pc-or-offset new
)))
934 (setf (node-end-pc-or-offset found
)
935 (max (node-end-pc-or-offset found
)
936 (node-end-pc-or-offset new
)))
939 (let ((call-count-info (gethash (node-name new
)
941 (when call-count-info
942 (setf (node-call-count new
)
943 (car call-count-info
))))
944 (setf (gethash key
*name-
>node
*) new
)
947 ;;; Return a list of all nodes created by LOOKUP-NODE.
948 (defun collect-nodes ()
949 (loop for node being the hash-values of
*name-
>node
*
952 ;;; Value is a CALL-GRAPH for the current contents of *SAMPLES*.
953 (defun make-call-graph-1 (max-depth)
954 (let ((elsewhere-count 0)
956 (with-lookup-tables ()
957 (loop for i below
(- (samples-index *samples
*) 2) by
2
959 for debug-info
= (aref (samples-vector *samples
*) i
)
960 for next-info
= (aref (samples-vector *samples
*)
962 do
(if (eq debug-info
'trace-start
)
964 (let ((callee (lookup-node debug-info
))
965 (caller (unless (eq next-info
'trace-start
)
966 (lookup-node next-info
))))
967 (when (< depth max-depth
)
969 (setf visited-nodes nil
)
971 (incf (node-accrued-count callee
))
972 (incf (node-count callee
)))
974 (incf elsewhere-count
))))
977 (push callee visited-nodes
))
979 (unless (member caller visited-nodes
)
980 (incf (node-accrued-count caller
)))
982 (let ((call (find callee
(node-edges caller
)
983 :key
#'call-vertex
)))
984 (pushnew caller
(node-callers callee
))
986 (unless (member caller visited-nodes
)
987 (incf (call-count call
)))
988 (push (make-call callee
)
989 (node-edges caller
))))))))))
990 (let ((sorted-nodes (sort (collect-nodes) #'> :key
#'node-count
)))
991 (loop for node in sorted-nodes and i from
1 do
992 (setf (node-index node
) i
))
993 (%make-call-graph
:nsamples
(samples-trace-count *samples
*)
994 :sample-interval
(if (eq (samples-mode *samples
*)
996 (samples-alloc-interval *samples
*)
997 (samples-sample-interval *samples
*))
998 :sampling-mode
(samples-mode *samples
*)
999 :sampled-threads
(samples-sampled-threads *samples
*)
1000 :elsewhere-count elsewhere-count
1001 :vertices sorted-nodes
)))))
1003 ;;; Reduce CALL-GRAPH to a dag, creating CYCLE structures for call
1005 (defun reduce-call-graph (call-graph)
1007 (flet ((make-one-cycle (vertices edges
)
1008 (let* ((name (format nil
"<Cycle ~d>" (incf cycle-no
)))
1009 (count (loop for v in vertices sum
(node-count v
))))
1010 (make-cycle :name name
1013 :scc-vertices vertices
1015 (reduce-graph call-graph
#'make-one-cycle
))))
1017 ;;; For all nodes in CALL-GRAPH, compute times including the time
1018 ;;; spent in functions called from them. Note that the call-graph
1019 ;;; vertices are in reverse topological order, children first, so we
1020 ;;; will have computed accrued counts of called functions before they
1021 ;;; are used to compute accrued counts for callers.
1022 (defun compute-accrued-counts (call-graph)
1023 (do-vertices (from call-graph
)
1024 (setf (node-accrued-count from
) (node-count from
))
1025 (do-edges (call to from
)
1026 (incf (node-accrued-count from
)
1027 (round (* (/ (call-count call
) (node-count to
))
1028 (node-accrued-count to
)))))))
1030 ;;; Return a CALL-GRAPH structure for the current contents of
1031 ;;; *SAMPLES*. The result contain a list of nodes sorted by self-time
1032 ;;; in the FLAT-NODES slot, and a dag in VERTICES, with call cycles
1033 ;;; reduced to CYCLE structures.
1034 (defun make-call-graph (max-depth)
1036 (show-progress "~&Computing call graph ")
1037 (let ((call-graph (without-gcing (make-call-graph-1 max-depth
))))
1038 (setf (call-graph-flat-nodes call-graph
)
1039 (copy-list (graph-vertices call-graph
)))
1040 (show-progress "~&Finding cycles")
1042 (reduce-call-graph call-graph
)
1043 (show-progress "~&Propagating counts")
1045 (compute-accrued-counts call-graph
)
1051 (defun print-separator (&key
(length 72) (char #\-
))
1052 (format t
"~&~V,,,V<~>~%" length char
))
1054 (defun samples-percent (call-graph count
)
1056 (* 100.0 (/ count
(call-graph-nsamples call-graph
)))
1059 (defun print-call-graph-header (call-graph)
1060 (let ((nsamples (call-graph-nsamples call-graph
))
1061 (interval (call-graph-sample-interval call-graph
))
1062 (ncycles (loop for v in
(graph-vertices call-graph
)
1064 (if (eq (call-graph-sampling-mode call-graph
) :alloc
)
1065 (format t
"~2&Number of samples: ~d~%~
1066 Alloc interval: ~a regions (approximately ~a kB)~%~
1067 Total sampling amount: ~a regions (approximately ~a kB)~%~
1068 Number of cycles: ~d~%~
1069 Sampled threads:~{~% ~S~}~2%"
1072 (truncate (* interval
*alloc-region-size
*) 1024)
1073 (* nsamples interval
)
1074 (truncate (* nsamples interval
*alloc-region-size
*) 1024)
1076 (call-graph-sampled-threads call-graph
))
1077 (format t
"~2&Number of samples: ~d~%~
1078 Sample interval: ~f seconds~%~
1079 Total sampling time: ~f seconds~%~
1080 Number of cycles: ~d~%~
1081 Sampled threads:~{~% ~S~}~2%"
1084 (* nsamples interval
)
1086 (call-graph-sampled-threads call-graph
)))))
1088 (declaim (type (member :samples
:cumulative-samples
) *report-sort-by
*))
1089 (defvar *report-sort-by
* :samples
1090 "Method for sorting the flat report: either by :SAMPLES or by :CUMULATIVE-SAMPLES.")
1092 (declaim (type (member :descending
:ascending
) *report-sort-order
*))
1093 (defvar *report-sort-order
* :descending
1094 "Order for sorting the flat report: either :DESCENDING or :ASCENDING.")
1096 (defun print-flat (call-graph &key
(stream *standard-output
*) max
1097 min-percent
(print-header t
)
1098 (sort-by *report-sort-by
*)
1099 (sort-order *report-sort-order
*))
1100 (declare (type (member :descending
:ascending
) sort-order
)
1101 (type (member :samples
:cumulative-samples
) sort-by
))
1102 (let ((*standard-output
* stream
)
1103 (*print-pretty
* nil
)
1106 (min-count (if min-percent
1107 (round (* (/ min-percent
100.0)
1108 (call-graph-nsamples call-graph
)))
1111 (print-call-graph-header call-graph
))
1112 (format t
"~& Self Total Cumul~%")
1113 (format t
"~& Nr Count % Count % Count % Calls Function~%")
1115 (let ((elsewhere-count (call-graph-elsewhere-count call-graph
))
1117 (nodes (stable-sort (copy-list (call-graph-flat-nodes call-graph
))
1118 (let ((cmp (if (eq :descending sort-order
) #'> #'<)))
1119 (multiple-value-bind (primary secondary
)
1120 (if (eq :samples sort-by
)
1121 (values #'node-count
#'node-accrued-count
)
1122 (values #'node-accrued-count
#'node-count
))
1124 (let ((cx (funcall primary x
))
1125 (cy (funcall primary y
)))
1127 (funcall cmp
(funcall secondary x
) (funcall secondary y
))
1128 (funcall cmp cx cy
)))))))))
1129 (dolist (node nodes
)
1130 (when (or (and max
(> (incf i
) max
))
1131 (< (node-count node
) min-count
))
1133 (let* ((count (node-count node
))
1134 (percent (samples-percent call-graph count
))
1135 (accrued-count (node-accrued-count node
))
1136 (accrued-percent (samples-percent call-graph accrued-count
)))
1137 (incf total-count count
)
1138 (incf total-percent percent
)
1139 (format t
"~&~4d ~6d ~5,1f ~6d ~5,1f ~6d ~5,1f ~8@a ~s~%"
1147 (or (node-call-count node
) "-")
1151 (format t
"~& ~6d ~5,1f~36a elsewhere~%"
1153 (samples-percent call-graph elsewhere-count
)
1156 (defun print-cycles (call-graph)
1157 (when (some #'cycle-p
(graph-vertices call-graph
))
1158 (format t
"~& Cycle~%")
1159 (format t
"~& Count % Parts~%")
1160 (do-vertices (node call-graph
)
1161 (when (cycle-p node
)
1162 (flet ((print-info (indent index count percent name
)
1163 (format t
"~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
1164 count percent indent name index
)))
1166 (format t
"~&~6d ~5,1f ~a...~%"
1168 (samples-percent call-graph
(cycle-count node
))
1170 (dolist (v (vertex-scc-vertices node
))
1171 (print-info 4 (node-index v
) (node-count v
)
1172 (samples-percent call-graph
(node-count v
))
1177 (defun print-graph (call-graph &key
(stream *standard-output
*)
1179 (let ((*standard-output
* stream
)
1180 (*print-pretty
* nil
))
1181 (print-call-graph-header call-graph
)
1182 (print-cycles call-graph
)
1183 (flet ((find-call (from to
)
1184 (find to
(node-edges from
) :key
#'call-vertex
))
1185 (print-info (indent index count percent name
)
1186 (format t
"~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
1187 count percent indent name index
)))
1188 (format t
"~& Callers~%")
1189 (format t
"~& Total. Function~%")
1190 (format t
"~& Count % Count % Callees~%")
1191 (do-vertices (node call-graph
)
1194 ;; Print caller information.
1195 (dolist (caller (node-callers node
))
1196 (let ((call (find-call caller node
)))
1197 (print-info 4 (node-index caller
)
1199 (samples-percent call-graph
(call-count call
))
1200 (node-name caller
))))
1201 ;; Print the node itself.
1202 (format t
"~&~6d ~5,1f ~6d ~5,1f ~s [~d]~%"
1204 (samples-percent call-graph
(node-count node
))
1205 (node-accrued-count node
)
1206 (samples-percent call-graph
(node-accrued-count node
))
1210 (do-edges (call called node
)
1211 (print-info 4 (node-index called
)
1213 (samples-percent call-graph
(call-count call
))
1214 (node-name called
))))
1217 (print-flat call-graph
:stream stream
:max max
1218 :min-percent min-percent
:print-header nil
))))
1220 (defun report (&key
(type :graph
) max min-percent call-graph
1221 ((:sort-by
*report-sort-by
*) *report-sort-by
*)
1222 ((:sort-order
*report-sort-order
*) *report-sort-order
*)
1223 (stream *standard-output
*) ((:show-progress
*show-progress
*)))
1224 "Report statistical profiling results. The following keyword
1225 args are recognized:
1228 Specifies the type of report to generate. If :FLAT, show
1229 flat report, if :GRAPH show a call graph and a flat report.
1230 If nil, don't print out a report.
1233 Specify a stream to print the report on. Default is
1237 Don't show more than <max> entries in the flat report.
1239 :MIN-PERCENT <min-percent>
1240 Don't show functions taking less than <min-percent> of the
1241 total time in the flat report.
1244 If :SAMPLES, sort flat report by number of samples taken.
1245 If :CUMULATIVE-SAMPLES, sort flat report by cumulative number of samples
1246 taken (shows how much time each function spent on stack.) Default
1247 is *REPORT-SORT-BY*.
1250 If :DESCENDING, sort flat report in descending order. If :ASCENDING,
1251 sort flat report in ascending order. Default is *REPORT-SORT-ORDER*.
1253 :SHOW-PROGRESS <bool>
1254 If true, print progress messages while generating the call graph.
1257 Print a report from <graph> instead of the latest profiling
1260 Value of this function is a CALL-GRAPH object representing the
1261 resulting call-graph, or NIL if there are no samples (eg. right after
1264 Profiling is stopped before the call graph is generated."
1266 (let ((graph (or call-graph
(make-call-graph most-positive-fixnum
))))
1269 (print-flat graph
:stream stream
:max max
:min-percent min-percent
))
1271 (print-graph graph
:stream stream
:max max
:min-percent min-percent
))
1275 (format stream
"~&; No samples to report.~%")
1278 ;;; Interface to DISASSEMBLE
1280 (defun sample-pc-from-pc-or-offset (sample pc-or-offset
)
1282 ;; Assembly routines or foreign functions don't move around, so we've
1284 ((or sb-kernel
:code-component string
)
1286 ;; Lisp functions might move, so we've stored a offset from the
1287 ;; start of the code component.
1288 (sb-di::compiled-debug-fun
1289 (let* ((component (sb-di::compiled-debug-fun-component sample
))
1290 (start-pc (code-start component
)))
1291 (+ start-pc pc-or-offset
)))))
1293 (defun add-disassembly-profile-note (chunk stream dstate
)
1294 (declare (ignore chunk stream
))
1296 (let* ((location (+ (sb-disassem::seg-virtual-location
1297 (sb-disassem:dstate-segment dstate
))
1298 (sb-disassem::dstate-cur-offs dstate
)))
1299 (samples (loop with index
= (samples-index *samples
*)
1300 for x from
0 below
(- index
2) by
2
1301 for last-sample
= nil then sample
1302 for sample
= (aref (samples-vector *samples
*) x
)
1303 for pc-or-offset
= (aref (samples-vector *samples
*)
1305 when
(and sample
(eq last-sample
'trace-start
))
1307 (sample-pc-from-pc-or-offset sample
1309 (unless (zerop samples
)
1310 (sb-disassem::note
(format nil
"~A/~A samples"
1311 samples
(samples-trace-count *samples
*))
1314 (pushnew 'add-disassembly-profile-note sb-disassem
::*default-dstate-hooks
*)
1319 ;;; The following functions tell sb-sprof to do call count profiling
1320 ;;; for the named functions in addition to normal statistical
1321 ;;; profiling. The benefit of this over using SB-PROFILE is that this
1322 ;;; encapsulation is a lot more lightweight, due to not needing to
1323 ;;; track cpu usage / consing. (For example, compiling asdf 20 times
1324 ;;; took 13s normally, 15s with call counting for all functions in
1325 ;;; SB-C, and 94s with SB-PROFILE profiling SB-C).
1327 (defun profile-call-counts (&rest names
)
1328 "Mark the functions named by NAMES as being subject to call counting
1329 during statistical profiling. If a string is used as a name, it will
1330 be interpreted as a package name. In this case call counting will be
1331 done for all functions with names like X or (SETF X), where X is a symbol
1332 with the package as its home package."
1333 (dolist (name names
)
1335 (let ((package (find-package name
)))
1336 (do-symbols (symbol package
)
1337 (when (eql (symbol-package symbol
) package
)
1338 (dolist (function-name (list symbol
(list 'setf symbol
)))
1339 (profile-call-counts-for-function function-name
)))))
1340 (profile-call-counts-for-function name
))))
1342 (defun profile-call-counts-for-function (function-name)
1343 (unless (gethash function-name
*encapsulations
*)
1344 (setf (gethash function-name
*encapsulations
*) nil
)))
1346 (defun unprofile-call-counts ()
1347 "Clear all call counting information. Call counting will be done for no
1348 functions during statistical profiling."
1349 (clrhash *encapsulations
*))
1351 ;;; Called when profiling is started to enable the call counting
1352 ;;; encapsulation. Wrap all the call counted functions
1353 (defun enable-call-counting ()
1354 (maphash (lambda (k v
)
1355 (declare (ignore v
))
1356 (enable-call-counting-for-function k
))
1359 ;;; Called when profiling is stopped to disable the encapsulation. Restore
1360 ;;; the original functions.
1361 (defun disable-call-counting ()
1362 (maphash (lambda (k v
)
1365 (without-package-locks
1366 (setf (fdefinition k
) (cdr v
)))
1367 (setf (cdr v
) nil
)))
1370 (defun enable-call-counting-for-function (function-name)
1371 (let ((info (gethash function-name
*encapsulations
*)))
1372 ;; We should never try to encapsulate an fdefn multiple times.
1373 (assert (or (null info
)
1375 (when (and (fboundp function-name
)
1376 (or (not (symbolp function-name
))
1377 (and (not (special-operator-p function-name
))
1378 (not (macro-function function-name
)))))
1379 (let* ((original-fun (fdefinition function-name
))
1380 (info (cons 0 original-fun
)))
1381 (setf (gethash function-name
*encapsulations
*) info
)
1382 (without-package-locks
1383 (setf (fdefinition function-name
)
1384 (sb-int:named-lambda call-counter
(sb-int:&more more-context more-count
)
1385 (declare (optimize speed
(safety 0)))
1386 ;; 2^59 calls should be enough for anybody, and it
1387 ;; allows using fixnum arithmetic on x86-64. 2^32
1388 ;; isn't enough, so we can't do that on 32 bit platforms.
1389 (incf (the (unsigned-byte 59)
1391 (multiple-value-call original-fun
1392 (sb-c:%more-arg-values more-context
1399 (defun test-0 (n &optional
(depth 0))
1400 (declare (optimize (debug 3)))
1403 (test-0 n
(1+ depth
))
1404 (test-0 n
(1+ depth
)))))
1407 (with-profiling (:reset t
:max-samples
1000 :report
:graph
)