Statprof restores previous sigprof handler when stopping
[bpt/guile.git] / module / statprof.scm
1 ;;;; (statprof) -- a statistical profiler for Guile
2 ;;;; -*-scheme-*-
3 ;;;;
4 ;;;; Copyright (C) 2009, 2010, 2011, 2013, 2014 Free Software Foundation, Inc.
5 ;;;; Copyright (C) 2004, 2009 Andy Wingo <wingo at pobox dot com>
6 ;;;; Copyright (C) 2001 Rob Browning <rlb at defaultvalue dot org>
7 ;;;;
8 ;;;; This library is free software; you can redistribute it and/or
9 ;;;; modify it under the terms of the GNU Lesser General Public
10 ;;;; License as published by the Free Software Foundation; either
11 ;;;; version 3 of the License, or (at your option) any later version.
12 ;;;;
13 ;;;; This library is distributed in the hope that it will be useful,
14 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ;;;; Lesser General Public License for more details.
17 ;;;;
18 ;;;; You should have received a copy of the GNU Lesser General Public
19 ;;;; License along with this library; if not, write to the Free Software
20 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 ;;;;
22 \f
23
24 ;;; Commentary:
25 ;;;
26 ;;; @code{(statprof)} is a statistical profiler for Guile.
27 ;;;
28 ;;; A simple use of statprof would look like this:
29 ;;;
30 ;;; @example
31 ;;; (statprof-reset 0 50000 #t)
32 ;;; (statprof-start)
33 ;;; (do-something)
34 ;;; (statprof-stop)
35 ;;; (statprof-display)
36 ;;; @end example
37 ;;;
38 ;;; This would reset statprof, clearing all accumulated statistics, then
39 ;;; start profiling, run some code, stop profiling, and finally display a
40 ;;; gprof flat-style table of statistics which will look something like
41 ;;; this:
42 ;;;
43 ;;; @example
44 ;;; % cumulative self self total
45 ;;; time seconds seconds calls ms/call ms/call name
46 ;;; 35.29 0.23 0.23 2002 0.11 0.11 -
47 ;;; 23.53 0.15 0.15 2001 0.08 0.08 positive?
48 ;;; 23.53 0.15 0.15 2000 0.08 0.08 +
49 ;;; 11.76 0.23 0.08 2000 0.04 0.11 do-nothing
50 ;;; 5.88 0.64 0.04 2001 0.02 0.32 loop
51 ;;; 0.00 0.15 0.00 1 0.00 150.59 do-something
52 ;;; ...
53 ;;; @end example
54 ;;;
55 ;;; All of the numerical data with the exception of the calls column is
56 ;;; statistically approximate. In the following column descriptions, and
57 ;;; in all of statprof, "time" refers to execution time (both user and
58 ;;; system), not wall clock time.
59 ;;;
60 ;;; @table @asis
61 ;;; @item % time
62 ;;; The percent of the time spent inside the procedure itself
63 ;;; (not counting children).
64 ;;; @item cumulative seconds
65 ;;; The total number of seconds spent in the procedure, including
66 ;;; children.
67 ;;; @item self seconds
68 ;;; The total number of seconds spent in the procedure itself (not counting
69 ;;; children).
70 ;;; @item calls
71 ;;; The total number of times the procedure was called.
72 ;;; @item self ms/call
73 ;;; The average time taken by the procedure itself on each call, in ms.
74 ;;; @item total ms/call
75 ;;; The average time taken by each call to the procedure, including time
76 ;;; spent in child functions.
77 ;;; @item name
78 ;;; The name of the procedure.
79 ;;; @end table
80 ;;;
81 ;;; The profiler uses @code{eq?} and the procedure object itself to
82 ;;; identify the procedures, so it won't confuse different procedures with
83 ;;; the same name. They will show up as two different rows in the output.
84 ;;;
85 ;;; Right now the profiler is quite simplistic. I cannot provide
86 ;;; call-graphs or other higher level information. What you see in the
87 ;;; table is pretty much all there is. Patches are welcome :-)
88 ;;;
89 ;;; @section Implementation notes
90 ;;;
91 ;;; The profiler works by setting the unix profiling signal
92 ;;; @code{ITIMER_PROF} to go off after the interval you define in the call
93 ;;; to @code{statprof-reset}. When the signal fires, a sampling routine is
94 ;;; run which looks at the current procedure that's executing, and then
95 ;;; crawls up the stack, and for each procedure encountered, increments
96 ;;; that procedure's sample count. Note that if a procedure is encountered
97 ;;; multiple times on a given stack, it is only counted once. After the
98 ;;; sampling is complete, the profiler resets profiling timer to fire
99 ;;; again after the appropriate interval.
100 ;;;
101 ;;; Meanwhile, the profiler keeps track, via @code{get-internal-run-time},
102 ;;; how much CPU time (system and user -- which is also what
103 ;;; @code{ITIMER_PROF} tracks), has elapsed while code has been executing
104 ;;; within a statprof-start/stop block.
105 ;;;
106 ;;; The profiler also tries to avoid counting or timing its own code as
107 ;;; much as possible.
108 ;;;
109 ;;; Code:
110
111 (define-module (statprof)
112 #:use-module (srfi srfi-1)
113 #:use-module (srfi srfi-9)
114 #:use-module (srfi srfi-9 gnu)
115 #:autoload (ice-9 format) (format)
116 #:use-module (system vm vm)
117 #:use-module (system vm frame)
118 #:use-module (system vm program)
119 #:export (statprof-active?
120 statprof-start
121 statprof-stop
122 statprof-reset
123
124 statprof-accumulated-time
125 statprof-sample-count
126 statprof-fold-call-data
127 statprof-proc-call-data
128 statprof-call-data-name
129 statprof-call-data-calls
130 statprof-call-data-cum-samples
131 statprof-call-data-self-samples
132 statprof-call-data->stats
133
134 statprof-stats-proc-name
135 statprof-stats-%-time-in-proc
136 statprof-stats-cum-secs-in-proc
137 statprof-stats-self-secs-in-proc
138 statprof-stats-calls
139 statprof-stats-self-secs-per-call
140 statprof-stats-cum-secs-per-call
141
142 statprof-display
143 statprof-display-anomalies
144 statprof-display-anomolies ; Deprecated spelling.
145
146 statprof-fetch-stacks
147 statprof-fetch-call-tree
148
149 statprof
150 with-statprof
151
152 gcprof))
153
154
155 ;; This profiler tracks two numbers for every function called while
156 ;; it's active. It tracks the total number of calls, and the number
157 ;; of times the function was active when the sampler fired.
158 ;;
159 ;; Globally the profiler tracks the total time elapsed and the number
160 ;; of times the sampler was fired.
161 ;;
162 ;; Right now, this profiler is not per-thread and is not thread safe.
163
164 (define-record-type <state>
165 (make-state accumulated-time last-start-time sample-count
166 sampling-period remaining-prof-time profile-level
167 count-calls? gc-time-taken record-full-stacks?
168 stacks procedure-data inside-profiler?
169 prev-sigprof-handler)
170 state?
171 ;; Total time so far.
172 (accumulated-time accumulated-time set-accumulated-time!)
173 ;; Start-time when timer is active.
174 (last-start-time last-start-time set-last-start-time!)
175 ;; Total count of sampler calls.
176 (sample-count sample-count set-sample-count!)
177 ;; Microseconds.
178 (sampling-period sampling-period set-sampling-period!)
179 ;; Time remaining when prof suspended.
180 (remaining-prof-time remaining-prof-time set-remaining-prof-time!)
181 ;; For user start/stop nesting.
182 (profile-level profile-level set-profile-level!)
183 ;; Whether to catch apply-frame.
184 (count-calls? count-calls? set-count-calls?!)
185 ;; GC time between statprof-start and statprof-stop.
186 (gc-time-taken gc-time-taken set-gc-time-taken!)
187 ;; If #t, stash away the stacks for future analysis.
188 (record-full-stacks? record-full-stacks? set-record-full-stacks?!)
189 ;; If record-full-stacks?, the stashed full stacks.
190 (stacks stacks set-stacks!)
191 ;; A hash where the key is the function object itself and the value is
192 ;; the data. The data will be a vector like this:
193 ;; #(name call-count cum-sample-count self-sample-count)
194 (procedure-data procedure-data set-procedure-data!)
195 ;; True if we are inside the profiler.
196 (inside-profiler? inside-profiler? set-inside-profiler?!)
197 ;; True if we are inside the profiler.
198 (prev-sigprof-handler prev-sigprof-handler set-prev-sigprof-handler!))
199
200 (define profiler-state (make-parameter #f))
201
202 (define* (fresh-profiler-state #:key (count-calls? #f)
203 (sampling-period 10000)
204 (full-stacks? #f))
205 (make-state 0 #f 0 sampling-period 0 0 count-calls? 0 #f '()
206 (make-hash-table) #f #f))
207
208 (define (ensure-profiler-state)
209 (or (profiler-state)
210 (let ((state (fresh-profiler-state)))
211 (profiler-state state)
212 state)))
213
214 (define (existing-profiler-state)
215 (or (profiler-state)
216 (error "expected there to be a profiler state")))
217
218 (define-record-type call-data
219 (make-call-data proc call-count cum-sample-count self-sample-count)
220 call-data?
221 (proc call-data-proc)
222 (call-count call-data-call-count set-call-data-call-count!)
223 (cum-sample-count call-data-cum-sample-count set-call-data-cum-sample-count!)
224 (self-sample-count call-data-self-sample-count set-call-data-self-sample-count!))
225
226 (define (call-data-name cd) (procedure-name (call-data-proc cd)))
227 (define (call-data-printable cd)
228 (or (call-data-name cd)
229 (with-output-to-string (lambda () (write (call-data-proc cd))))))
230
231 (define (inc-call-data-call-count! cd)
232 (set-call-data-call-count! cd (1+ (call-data-call-count cd))))
233 (define (inc-call-data-cum-sample-count! cd)
234 (set-call-data-cum-sample-count! cd (1+ (call-data-cum-sample-count cd))))
235 (define (inc-call-data-self-sample-count! cd)
236 (set-call-data-self-sample-count! cd (1+ (call-data-self-sample-count cd))))
237
238 (define (accumulate-time state stop-time)
239 (set-accumulated-time! state
240 (+ (accumulated-time state)
241 (- stop-time (last-start-time state)))))
242
243 (define (get-call-data state proc)
244 (let ((k (cond
245 ((program? proc) (program-code proc))
246 (else proc))))
247 (or (hashv-ref (procedure-data state) k)
248 (let ((call-data (make-call-data proc 0 0 0)))
249 (hashv-set! (procedure-data state) k call-data)
250 call-data))))
251
252 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
253 ;; SIGPROF handler
254
255 ;; FIXME: Instead of this messing about with hash tables and
256 ;; frame-procedure, just record the stack of return addresses into a
257 ;; growable vector, and resolve them to procedures when analyzing
258 ;; instead of at collection time.
259 ;;
260 (define (sample-stack-procs state stack)
261 (let ((stacklen (stack-length stack))
262 (hit-count-call? #f))
263
264 (when (record-full-stacks? state)
265 (set-stacks! state (cons stack (stacks state))))
266
267 (set-sample-count! state (+ (sample-count state) 1))
268 ;; Now accumulate stats for the whole stack.
269 (let loop ((frame (stack-ref stack 0))
270 (procs-seen (make-hash-table 13))
271 (self #f))
272 (cond
273 ((not frame)
274 (hash-fold
275 (lambda (proc val accum)
276 (inc-call-data-cum-sample-count!
277 (get-call-data state proc)))
278 #f
279 procs-seen)
280 (and=> (and=> self (lambda (proc)
281 (get-call-data state proc)))
282 inc-call-data-self-sample-count!))
283 ((frame-procedure frame)
284 => (lambda (proc)
285 (cond
286 ((eq? proc count-call)
287 ;; We're not supposed to be sampling count-call and
288 ;; its sub-functions, so loop again with a clean
289 ;; slate.
290 (set! hit-count-call? #t)
291 (loop (frame-previous frame) (make-hash-table 13) #f))
292 (else
293 (hashq-set! procs-seen proc #t)
294 (loop (frame-previous frame)
295 procs-seen
296 (or self proc))))))
297 (else
298 (loop (frame-previous frame) procs-seen self))))
299 hit-count-call?))
300
301 (define (reset-sigprof-timer usecs)
302 ;; Guile's setitimer binding is terrible.
303 (let ((prev (setitimer ITIMER_PROF 0 0 0 usecs)))
304 (+ (* (caadr prev) #e1e6) (cdadr prev))))
305
306 (define (profile-signal-handler sig)
307 (define state (existing-profiler-state))
308
309 (set-inside-profiler?! state #t)
310
311 ;; FIXME: with-statprof should be able to set an outer frame for the
312 ;; stack cut
313 (when (positive? (profile-level state))
314 (let* ((stop-time (get-internal-run-time))
315 ;; cut down to the signal handler. note that this will only
316 ;; work if statprof.scm is compiled; otherwise we get
317 ;; `eval' on the stack instead, because if it's not
318 ;; compiled, profile-signal-handler is a thunk that
319 ;; tail-calls eval. perhaps we should always compile the
320 ;; signal handler instead...
321 (stack (or (make-stack #t profile-signal-handler)
322 (pk 'what! (make-stack #t)))))
323
324 (sample-stack-procs state stack)
325 (accumulate-time state stop-time)
326 (set-last-start-time! state (get-internal-run-time))
327
328 (reset-sigprof-timer (sampling-period state))))
329
330 (set-inside-profiler?! state #f))
331
332 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
333 ;; Count total calls.
334
335 (define (count-call frame)
336 (define state (existing-profiler-state))
337
338 (unless (inside-profiler? state)
339 (accumulate-time state (get-internal-run-time))
340
341 (and=> (frame-procedure frame)
342 (lambda (proc)
343 (inc-call-data-call-count!
344 (get-call-data state proc))))
345
346 (set-last-start-time! state (get-internal-run-time))))
347
348 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
349
350 (define (statprof-active?)
351 "Returns @code{#t} if @code{statprof-start} has been called more times
352 than @code{statprof-stop}, @code{#f} otherwise."
353 (define state (profiler-state))
354 (and state (positive? (profile-level state))))
355
356 ;; Do not call this from statprof internal functions -- user only.
357 (define (statprof-start)
358 "Start the profiler.@code{}"
359 ;; After some head-scratching, I don't *think* I need to mask/unmask
360 ;; signals here, but if I'm wrong, please let me know.
361 (define state (ensure-profiler-state))
362 (set-profile-level! state (+ (profile-level state) 1))
363 (when (= (profile-level state) 1)
364 (let ((rpt (remaining-prof-time state)))
365 (set-remaining-prof-time! state 0)
366 ;; FIXME: Use per-thread run time.
367 (set-last-start-time! state (get-internal-run-time))
368 (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
369 (let ((prev (sigaction SIGPROF profile-signal-handler)))
370 (set-prev-sigprof-handler! state (car prev)))
371 (reset-sigprof-timer (if (zero? rpt) (sampling-period state) rpt))
372 (when (count-calls? state)
373 (add-hook! (vm-apply-hook) count-call))
374 (set-vm-trace-level! (1+ (vm-trace-level)))
375 #t)))
376
377 ;; Do not call this from statprof internal functions -- user only.
378 (define (statprof-stop)
379 "Stop the profiler.@code{}"
380 ;; After some head-scratching, I don't *think* I need to mask/unmask
381 ;; signals here, but if I'm wrong, please let me know.
382 (define state (ensure-profiler-state))
383 (set-profile-level! state (- (profile-level state) 1))
384 (when (zero? (profile-level state))
385 (set-gc-time-taken! state
386 (- (assq-ref (gc-stats) 'gc-time-taken)
387 (gc-time-taken state)))
388 (set-vm-trace-level! (1- (vm-trace-level)))
389 (when (count-calls? state)
390 (remove-hook! (vm-apply-hook) count-call))
391 ;; I believe that we need to do this before getting the time
392 ;; (unless we want to make things even more complicated).
393 (set-remaining-prof-time! state (reset-sigprof-timer 0))
394 (accumulate-time state (get-internal-run-time))
395 (sigaction SIGPROF (prev-sigprof-handler state))
396 (set-prev-sigprof-handler! state #f)
397 (set-last-start-time! state #f)))
398
399 (define* (statprof-reset sample-seconds sample-microseconds count-calls?
400 #:optional full-stacks?)
401 "Reset the statprof sampler interval to @var{sample-seconds} and
402 @var{sample-microseconds}. If @var{count-calls?} is true, arrange to
403 instrument procedure calls as well as collecting statistical profiling
404 data. If @var{full-stacks?} is true, collect all sampled stacks into a
405 list for later analysis.
406
407 Enables traps and debugging as necessary."
408 (when (statprof-active?)
409 (error "Can't reset profiler while profiler is running."))
410 (profiler-state
411 (fresh-profiler-state #:count-calls? count-calls?
412 #:sampling-period (+ (* sample-seconds #e1e6)
413 sample-microseconds)
414 #:full-stacks? full-stacks?)))
415
416 (define (statprof-fold-call-data proc init)
417 "Fold @var{proc} over the call-data accumulated by statprof. Cannot be
418 called while statprof is active. @var{proc} should take two arguments,
419 @code{(@var{call-data} @var{prior-result})}.
420
421 Note that a given proc-name may appear multiple times, but if it does,
422 it represents different functions with the same name."
423 (when (statprof-active?)
424 (error "Can't call statprof-fold-call-data while profiler is running."))
425 (hash-fold
426 (lambda (key value prior-result)
427 (proc value prior-result))
428 init
429 (procedure-data (existing-profiler-state))))
430
431 (define (statprof-proc-call-data proc)
432 "Returns the call-data associated with @var{proc}, or @code{#f} if
433 none is available."
434 (when (statprof-active?)
435 (error "Can't call statprof-proc-call-data while profiler is running."))
436 (get-call-data (existing-profiler-state) proc))
437
438 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
439 ;; Stats
440
441 (define (statprof-call-data->stats call-data)
442 "Returns an object of type @code{statprof-stats}."
443 ;; returns (vector proc-name
444 ;; %-time-in-proc
445 ;; cum-seconds-in-proc
446 ;; self-seconds-in-proc
447 ;; num-calls
448 ;; self-secs-per-call
449 ;; total-secs-per-call)
450
451 (define state (existing-profiler-state))
452
453 (let* ((proc-name (call-data-printable call-data))
454 (self-samples (call-data-self-sample-count call-data))
455 (cum-samples (call-data-cum-sample-count call-data))
456 (all-samples (statprof-sample-count))
457 (secs-per-sample (/ (statprof-accumulated-time)
458 (statprof-sample-count)))
459 (num-calls (and (count-calls? state) (statprof-call-data-calls call-data))))
460
461 (vector proc-name
462 (* (/ self-samples all-samples) 100.0)
463 (* cum-samples secs-per-sample 1.0)
464 (* self-samples secs-per-sample 1.0)
465 num-calls
466 (and num-calls ;; maybe we only sampled in children
467 (if (zero? self-samples) 0.0
468 (/ (* self-samples secs-per-sample) 1.0 num-calls)))
469 (and num-calls ;; cum-samples must be positive
470 (/ (* cum-samples secs-per-sample)
471 1.0
472 ;; num-calls might be 0 if we entered statprof during the
473 ;; dynamic extent of the call
474 (max num-calls 1))))))
475
476 (define (statprof-stats-proc-name stats) (vector-ref stats 0))
477 (define (statprof-stats-%-time-in-proc stats) (vector-ref stats 1))
478 (define (statprof-stats-cum-secs-in-proc stats) (vector-ref stats 2))
479 (define (statprof-stats-self-secs-in-proc stats) (vector-ref stats 3))
480 (define (statprof-stats-calls stats) (vector-ref stats 4))
481 (define (statprof-stats-self-secs-per-call stats) (vector-ref stats 5))
482 (define (statprof-stats-cum-secs-per-call stats) (vector-ref stats 6))
483
484 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
485
486 (define (stats-sorter x y)
487 (let ((diff (- (statprof-stats-self-secs-in-proc x)
488 (statprof-stats-self-secs-in-proc y))))
489 (positive?
490 (if (= diff 0)
491 (- (statprof-stats-cum-secs-in-proc x)
492 (statprof-stats-cum-secs-in-proc y))
493 diff))))
494
495 (define* (statprof-display #:optional (port (current-output-port))
496 (state (existing-profiler-state)))
497 "Displays a gprof-like summary of the statistics collected. Unless an
498 optional @var{port} argument is passed, uses the current output port."
499 (cond
500 ((zero? (statprof-sample-count))
501 (format port "No samples recorded.\n"))
502 (else
503 (let* ((stats-list (statprof-fold-call-data
504 (lambda (data prior-value)
505 (cons (statprof-call-data->stats data)
506 prior-value))
507 '()))
508 (sorted-stats (sort stats-list stats-sorter)))
509
510 (define (display-stats-line stats)
511 (if (count-calls? state)
512 (format port "~6,2f ~9,2f ~9,2f ~7d ~8,2f ~8,2f "
513 (statprof-stats-%-time-in-proc stats)
514 (statprof-stats-cum-secs-in-proc stats)
515 (statprof-stats-self-secs-in-proc stats)
516 (statprof-stats-calls stats)
517 (* 1000 (statprof-stats-self-secs-per-call stats))
518 (* 1000 (statprof-stats-cum-secs-per-call stats)))
519 (format port "~6,2f ~9,2f ~9,2f "
520 (statprof-stats-%-time-in-proc stats)
521 (statprof-stats-cum-secs-in-proc stats)
522 (statprof-stats-self-secs-in-proc stats)))
523 (display (statprof-stats-proc-name stats) port)
524 (newline port))
525
526 (if (count-calls? state)
527 (begin
528 (format port "~5a ~10a ~7a ~8a ~8a ~8a ~8@a\n"
529 "% " "cumulative" "self" "" "self" "total" "")
530 (format port "~5a ~9a ~8a ~8a ~8a ~8a ~8@a\n"
531 "time" "seconds" "seconds" "calls" "ms/call" "ms/call" "name"))
532 (begin
533 (format port "~5a ~10a ~7a ~8@a\n"
534 "%" "cumulative" "self" "")
535 (format port "~5a ~10a ~7a ~8@a\n"
536 "time" "seconds" "seconds" "name")))
537
538 (for-each display-stats-line sorted-stats)
539
540 (display "---\n" port)
541 (simple-format #t "Sample count: ~A\n" (statprof-sample-count))
542 (simple-format #t "Total time: ~A seconds (~A seconds in GC)\n"
543 (statprof-accumulated-time)
544 (/ (gc-time-taken state)
545 1.0 internal-time-units-per-second))))))
546
547 (define* (statprof-display-anomalies #:optional (state
548 (existing-profiler-state)))
549 "A sanity check that attempts to detect anomalies in statprof's
550 statistics.@code{}"
551 (statprof-fold-call-data
552 (lambda (data prior-value)
553 (when (and (count-calls? state)
554 (zero? (call-data-call-count data))
555 (positive? (call-data-cum-sample-count data)))
556 (simple-format #t
557 "==[~A ~A ~A]\n"
558 (call-data-name data)
559 (call-data-call-count data)
560 (call-data-cum-sample-count data))))
561 #f)
562 (simple-format #t "Total time: ~A\n" (statprof-accumulated-time))
563 (simple-format #t "Sample count: ~A\n" (statprof-sample-count)))
564
565 (define (statprof-display-anomolies)
566 (issue-deprecation-warning "statprof-display-anomolies is a misspelling. "
567 "Use statprof-display-anomalies instead.")
568 (statprof-display-anomalies))
569
570 (define* (statprof-accumulated-time #:optional (state
571 (existing-profiler-state)))
572 "Returns the time accumulated during the last statprof run.@code{}"
573 (/ (accumulated-time state) 1.0 internal-time-units-per-second))
574
575 (define* (statprof-sample-count #:optional (state (existing-profiler-state)))
576 "Returns the number of samples taken during the last statprof run.@code{}"
577 (sample-count state))
578
579 (define statprof-call-data-name call-data-name)
580 (define statprof-call-data-calls call-data-call-count)
581 (define statprof-call-data-cum-samples call-data-cum-sample-count)
582 (define statprof-call-data-self-samples call-data-self-sample-count)
583
584 (define* (statprof-fetch-stacks #:optional (state (existing-profiler-state)))
585 "Returns a list of stacks, as they were captured since the last call
586 to @code{statprof-reset}.
587
588 Note that stacks are only collected if the @var{full-stacks?} argument
589 to @code{statprof-reset} is true."
590 (stacks state))
591
592 (define procedure=?
593 (lambda (a b)
594 (cond
595 ((eq? a b))
596 ((and (program? a) (program? b))
597 (eq? (program-code a) (program-code b)))
598 (else
599 #f))))
600
601 ;; tree ::= (car n . tree*)
602
603 (define (lists->trees lists equal?)
604 (let lp ((in lists) (n-terminal 0) (tails '()))
605 (cond
606 ((null? in)
607 (let ((trees (map (lambda (tail)
608 (cons (car tail)
609 (lists->trees (cdr tail) equal?)))
610 tails)))
611 (cons (apply + n-terminal (map cadr trees))
612 (sort trees
613 (lambda (a b) (> (cadr a) (cadr b)))))))
614 ((null? (car in))
615 (lp (cdr in) (1+ n-terminal) tails))
616 ((find (lambda (x) (equal? (car x) (caar in)))
617 tails)
618 => (lambda (tail)
619 (lp (cdr in)
620 n-terminal
621 (assq-set! tails
622 (car tail)
623 (cons (cdar in) (cdr tail))))))
624 (else
625 (lp (cdr in)
626 n-terminal
627 (acons (caar in) (list (cdar in)) tails))))))
628
629 (define (stack->procedures stack)
630 (filter identity
631 (unfold-right (lambda (x) (not x))
632 frame-procedure
633 frame-previous
634 (stack-ref stack 0))))
635
636 (define* (statprof-fetch-call-tree #:optional (state (existing-profiler-state)))
637 "Return a call tree for the previous statprof run.
638
639 The return value is a list of nodes, each of which is of the type:
640 @code
641 node ::= (@var{proc} @var{count} . @var{nodes})
642 @end code"
643 (cons #t (lists->trees (map stack->procedures (stacks state)) procedure=?)))
644
645 (define* (statprof thunk #:key (loop 1) (hz 100) (count-calls? #f)
646 (full-stacks? #f))
647 "Profiles the execution of @var{thunk}.
648
649 The stack will be sampled @var{hz} times per second, and the thunk itself will
650 be called @var{loop} times.
651
652 If @var{count-calls?} is true, all procedure calls will be recorded. This
653 operation is somewhat expensive.
654
655 If @var{full-stacks?} is true, at each sample, statprof will store away the
656 whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
657 @code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
658
659 (let ((state (fresh-profiler-state)))
660 (parameterize ((profiler-state state))
661 (dynamic-wind
662 (lambda ()
663 (statprof-reset 0
664 (inexact->exact (round (/ 1e6 hz)))
665 count-calls?
666 full-stacks?)
667 (statprof-start))
668 (lambda ()
669 (let lp ((i loop))
670 (unless (zero? i)
671 (thunk)
672 (lp (1- i)))))
673 (lambda ()
674 (statprof-stop)
675 (statprof-display))))))
676
677 (define-macro (with-statprof . args)
678 "Profiles the expressions in its body.
679
680 Keyword arguments:
681
682 @table @code
683 @item #:loop
684 Execute the body @var{loop} number of times, or @code{#f} for no looping
685
686 default: @code{#f}
687 @item #:hz
688 Sampling rate
689
690 default: @code{20}
691 @item #:count-calls?
692 Whether to instrument each function call (expensive)
693
694 default: @code{#f}
695 @item #:full-stacks?
696 Whether to collect away all sampled stacks into a list
697
698 default: @code{#f}
699 @end table"
700 (define (kw-arg-ref kw args def)
701 (cond
702 ((null? args) (error "Invalid macro body"))
703 ((keyword? (car args))
704 (if (eq? (car args) kw)
705 (cadr args)
706 (kw-arg-ref kw (cddr args) def)))
707 ((eq? kw #f def) ;; asking for the body
708 args)
709 (else def))) ;; kw not found
710 `((@ (statprof) statprof)
711 (lambda () ,@(kw-arg-ref #f args #f))
712 #:loop ,(kw-arg-ref #:loop args 1)
713 #:hz ,(kw-arg-ref #:hz args 100)
714 #:count-calls? ,(kw-arg-ref #:count-calls? args #f)
715 #:full-stacks? ,(kw-arg-ref #:full-stacks? args #f)))
716
717 (define* (gcprof thunk #:key (loop 1) (full-stacks? #f))
718 "Do an allocation profile of the execution of @var{thunk}.
719
720 The stack will be sampled soon after every garbage collection, yielding
721 an approximate idea of what is causing allocation in your program.
722
723 Since GC does not occur very frequently, you may need to use the
724 @var{loop} parameter, to cause @var{thunk} to be called @var{loop}
725 times.
726
727 If @var{full-stacks?} is true, at each sample, statprof will store away the
728 whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
729 @code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
730
731 (let ((state (fresh-profiler-state #:full-stacks? full-stacks?)))
732 (parameterize ((profiler-state state))
733 (define (gc-callback)
734 (unless (inside-profiler? state)
735 (set-inside-profiler?! state #t)
736
737 ;; FIXME: should be able to set an outer frame for the stack cut
738 (let ((stop-time (get-internal-run-time))
739 ;; Cut down to gc-callback, and then one before (the
740 ;; after-gc async). See the note in profile-signal-handler
741 ;; also.
742 (stack (or (make-stack #t gc-callback 0 1)
743 (pk 'what! (make-stack #t)))))
744 (sample-stack-procs state stack)
745 (accumulate-time state stop-time)
746 (set-last-start-time! state (get-internal-run-time)))
747
748 (set-inside-profiler?! state #f)))
749
750 (dynamic-wind
751 (lambda ()
752 (set-profile-level! state 1)
753 (set-last-start-time! state (get-internal-run-time))
754 (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
755 (add-hook! after-gc-hook gc-callback))
756 (lambda ()
757 (let lp ((i loop))
758 (unless (zero? i)
759 (thunk)
760 (lp (1- i)))))
761 (lambda ()
762 (remove-hook! after-gc-hook gc-callback)
763 (set-gc-time-taken! state
764 (- (assq-ref (gc-stats) 'gc-time-taken)
765 (gc-time-taken state)))
766 (accumulate-time state (get-internal-run-time))
767 (set-profile-level! state 0)
768 (statprof-display))))))