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