print: In R7RS |...| symbols, print most graphic characters unescaped.
[bpt/guile.git] / module / statprof.scm
1 ;;;; (statprof) -- a statistical profiler for Guile
2 ;;;; -*-scheme-*-
3 ;;;;
4 ;;;; Copyright (C) 2009, 2010, 2011 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 (if (or (not (program? proc))
220 (zero? (program-num-free-variables proc)))
221 proc
222 (program-objcode proc))))
223 (or (hashq-ref procedure-data k)
224 (let ((call-data (make-call-data proc 0 0 0)))
225 (hashq-set! procedure-data k call-data)
226 call-data))))
227
228 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
229 ;; SIGPROF handler
230
231 (define (sample-stack-procs stack)
232 (let ((stacklen (stack-length stack))
233 (hit-count-call? #f))
234
235 (if record-full-stacks?
236 (set! stacks (cons stack stacks)))
237
238 (set! sample-count (+ sample-count 1))
239 ;; Now accumulate stats for the whole stack.
240 (let loop ((frame (stack-ref stack 0))
241 (procs-seen (make-hash-table 13))
242 (self #f))
243 (cond
244 ((not frame)
245 (hash-fold
246 (lambda (proc val accum)
247 (inc-call-data-cum-sample-count!
248 (get-call-data proc)))
249 #f
250 procs-seen)
251 (and=> (and=> self get-call-data)
252 inc-call-data-self-sample-count!))
253 ((frame-procedure frame)
254 => (lambda (proc)
255 (cond
256 ((eq? proc count-call)
257 ;; We're not supposed to be sampling count-call and
258 ;; its sub-functions, so loop again with a clean
259 ;; slate.
260 (set! hit-count-call? #t)
261 (loop (frame-previous frame) (make-hash-table 13) #f))
262 (else
263 (hashq-set! procs-seen proc #t)
264 (loop (frame-previous frame)
265 procs-seen
266 (or self proc))))))
267 (else
268 (loop (frame-previous frame) procs-seen self))))
269 hit-count-call?))
270
271 (define inside-profiler? #f)
272
273 (define (profile-signal-handler sig)
274 (set! inside-profiler? #t)
275
276 ;; FIXME: with-statprof should be able to set an outer frame for the
277 ;; stack cut
278 (if (positive? profile-level)
279 (let* ((stop-time (get-internal-run-time))
280 ;; cut down to the signal handler. note that this will only
281 ;; work if statprof.scm is compiled; otherwise we get
282 ;; `eval' on the stack instead, because if it's not
283 ;; compiled, profile-signal-handler is a thunk that
284 ;; tail-calls eval. perhaps we should always compile the
285 ;; signal handler instead...
286 (stack (or (make-stack #t profile-signal-handler)
287 (pk 'what! (make-stack #t))))
288 (inside-apply-trap? (sample-stack-procs stack)))
289
290 (if (not inside-apply-trap?)
291 (begin
292 ;; disabling here is just a little more efficient, but
293 ;; not necessary given inside-profiler?. We can't just
294 ;; disable unconditionally at the top of this function
295 ;; and eliminate inside-profiler? because it seems to
296 ;; confuse guile wrt re-enabling the trap when
297 ;; count-call finishes.
298 (if %count-calls?
299 (set-vm-trace-level! (the-vm)
300 (1- (vm-trace-level (the-vm)))))
301 (accumulate-time stop-time)))
302
303 (setitimer ITIMER_PROF
304 0 0
305 (car sampling-frequency)
306 (cdr sampling-frequency))
307
308 (if (not inside-apply-trap?)
309 (begin
310 (set! last-start-time (get-internal-run-time))
311 (if %count-calls?
312 (set-vm-trace-level! (the-vm)
313 (1+ (vm-trace-level (the-vm)))))))))
314
315 (set! inside-profiler? #f))
316
317 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
318 ;; Count total calls.
319
320 (define (count-call frame)
321 (if (not inside-profiler?)
322 (begin
323 (accumulate-time (get-internal-run-time))
324
325 (and=> (frame-procedure frame)
326 (lambda (proc)
327 (inc-call-data-call-count!
328 (get-call-data proc))))
329
330 (set! last-start-time (get-internal-run-time)))))
331
332 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
333
334 (define (statprof-active?)
335 "Returns @code{#t} if @code{statprof-start} has been called more times
336 than @code{statprof-stop}, @code{#f} otherwise."
337 (positive? profile-level))
338
339 ;; Do not call this from statprof internal functions -- user only.
340 (define (statprof-start)
341 "Start the profiler.@code{}"
342 ;; After some head-scratching, I don't *think* I need to mask/unmask
343 ;; signals here, but if I'm wrong, please let me know.
344 (set! profile-level (+ profile-level 1))
345 (if (= profile-level 1)
346 (let* ((rpt remaining-prof-time)
347 (use-rpt? (and rpt
348 (or (positive? (car rpt))
349 (positive? (cdr rpt))))))
350 (set! remaining-prof-time #f)
351 (set! last-start-time (get-internal-run-time))
352 (set! gc-time-taken
353 (cdr (assq 'gc-time-taken (gc-stats))))
354 (if use-rpt?
355 (setitimer ITIMER_PROF 0 0 (car rpt) (cdr rpt))
356 (setitimer ITIMER_PROF
357 0 0
358 (car sampling-frequency)
359 (cdr sampling-frequency)))
360 (if %count-calls?
361 (add-hook! (vm-apply-hook (the-vm)) count-call))
362 (set-vm-trace-level! (the-vm) (1+ (vm-trace-level (the-vm))))
363 #t)))
364
365 ;; Do not call this from statprof internal functions -- user only.
366 (define (statprof-stop)
367 "Stop the profiler.@code{}"
368 ;; After some head-scratching, I don't *think* I need to mask/unmask
369 ;; signals here, but if I'm wrong, please let me know.
370 (set! profile-level (- profile-level 1))
371 (if (zero? profile-level)
372 (begin
373 (set! gc-time-taken
374 (- (cdr (assq 'gc-time-taken (gc-stats))) gc-time-taken))
375 (set-vm-trace-level! (the-vm) (1- (vm-trace-level (the-vm))))
376 (if %count-calls?
377 (remove-hook! (vm-apply-hook (the-vm)) count-call))
378 ;; I believe that we need to do this before getting the time
379 ;; (unless we want to make things even more complicated).
380 (set! remaining-prof-time (setitimer ITIMER_PROF 0 0 0 0))
381 (accumulate-time (get-internal-run-time))
382 (set! last-start-time #f))))
383
384 (define* (statprof-reset sample-seconds sample-microseconds count-calls?
385 #:optional full-stacks?)
386 "Reset the statprof sampler interval to @var{sample-seconds} and
387 @var{sample-microseconds}. If @var{count-calls?} is true, arrange to
388 instrument procedure calls as well as collecting statistical profiling
389 data. If @var{full-stacks?} is true, collect all sampled stacks into a
390 list for later analysis.
391
392 Enables traps and debugging as necessary."
393 (if (positive? profile-level)
394 (error "Can't reset profiler while profiler is running."))
395 (set! %count-calls? count-calls?)
396 (set! accumulated-time 0)
397 (set! last-start-time #f)
398 (set! sample-count 0)
399 (set! sampling-frequency (cons sample-seconds sample-microseconds))
400 (set! remaining-prof-time #f)
401 (set! procedure-data (make-hash-table 131))
402 (set! record-full-stacks? full-stacks?)
403 (set! stacks '())
404 (sigaction SIGPROF profile-signal-handler)
405 #t)
406
407 (define (statprof-fold-call-data proc init)
408 "Fold @var{proc} over the call-data accumulated by statprof. Cannot be
409 called while statprof is active. @var{proc} should take two arguments,
410 @code{(@var{call-data} @var{prior-result})}.
411
412 Note that a given proc-name may appear multiple times, but if it does,
413 it represents different functions with the same name."
414 (if (positive? profile-level)
415 (error "Can't call statprof-fold-called while profiler is running."))
416
417 (hash-fold
418 (lambda (key value prior-result)
419 (proc value prior-result))
420 init
421 procedure-data))
422
423 (define (statprof-proc-call-data proc)
424 "Returns the call-data associated with @var{proc}, or @code{#f} if
425 none is available."
426 (if (positive? profile-level)
427 (error "Can't call statprof-fold-called while profiler is running."))
428
429 (hashq-ref procedure-data proc))
430
431 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
432 ;; Stats
433
434 (define (statprof-call-data->stats call-data)
435 "Returns an object of type @code{statprof-stats}."
436 ;; returns (vector proc-name
437 ;; %-time-in-proc
438 ;; cum-seconds-in-proc
439 ;; self-seconds-in-proc
440 ;; num-calls
441 ;; self-secs-per-call
442 ;; total-secs-per-call)
443
444 (let* ((proc-name (call-data-printable call-data))
445 (self-samples (call-data-self-sample-count call-data))
446 (cum-samples (call-data-cum-sample-count call-data))
447 (all-samples (statprof-sample-count))
448 (secs-per-sample (/ (statprof-accumulated-time)
449 (statprof-sample-count)))
450 (num-calls (and %count-calls? (statprof-call-data-calls call-data))))
451
452 (vector proc-name
453 (* (/ self-samples all-samples) 100.0)
454 (* cum-samples secs-per-sample 1.0)
455 (* self-samples secs-per-sample 1.0)
456 num-calls
457 (and num-calls ;; maybe we only sampled in children
458 (if (zero? self-samples) 0.0
459 (/ (* self-samples secs-per-sample) 1.0 num-calls)))
460 (and num-calls ;; cum-samples must be positive
461 (/ (* cum-samples secs-per-sample)
462 1.0
463 ;; num-calls might be 0 if we entered statprof during the
464 ;; dynamic extent of the call
465 (max num-calls 1))))))
466
467 (define (statprof-stats-proc-name stats) (vector-ref stats 0))
468 (define (statprof-stats-%-time-in-proc stats) (vector-ref stats 1))
469 (define (statprof-stats-cum-secs-in-proc stats) (vector-ref stats 2))
470 (define (statprof-stats-self-secs-in-proc stats) (vector-ref stats 3))
471 (define (statprof-stats-calls stats) (vector-ref stats 4))
472 (define (statprof-stats-self-secs-per-call stats) (vector-ref stats 5))
473 (define (statprof-stats-cum-secs-per-call stats) (vector-ref stats 6))
474
475 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
476
477 (define (stats-sorter x y)
478 (let ((diff (- (statprof-stats-self-secs-in-proc x)
479 (statprof-stats-self-secs-in-proc y))))
480 (positive?
481 (if (= diff 0)
482 (- (statprof-stats-cum-secs-in-proc x)
483 (statprof-stats-cum-secs-in-proc y))
484 diff))))
485
486 (define (statprof-display . port)
487 "Displays a gprof-like summary of the statistics collected. Unless an
488 optional @var{port} argument is passed, uses the current output port."
489 (if (null? port) (set! port (current-output-port)))
490
491 (cond
492 ((zero? (statprof-sample-count))
493 (format port "No samples recorded.\n"))
494 (else
495 (let* ((stats-list (statprof-fold-call-data
496 (lambda (data prior-value)
497 (cons (statprof-call-data->stats data)
498 prior-value))
499 '()))
500 (sorted-stats (sort stats-list stats-sorter)))
501
502 (define (display-stats-line stats)
503 (if %count-calls?
504 (format port "~6,2f ~9,2f ~9,2f ~7d ~8,2f ~8,2f "
505 (statprof-stats-%-time-in-proc stats)
506 (statprof-stats-cum-secs-in-proc stats)
507 (statprof-stats-self-secs-in-proc stats)
508 (statprof-stats-calls stats)
509 (* 1000 (statprof-stats-self-secs-per-call stats))
510 (* 1000 (statprof-stats-cum-secs-per-call stats)))
511 (format port "~6,2f ~9,2f ~9,2f "
512 (statprof-stats-%-time-in-proc stats)
513 (statprof-stats-cum-secs-in-proc stats)
514 (statprof-stats-self-secs-in-proc stats)))
515 (display (statprof-stats-proc-name stats) port)
516 (newline port))
517
518 (if %count-calls?
519 (begin
520 (format port "~5a ~10a ~7a ~8a ~8a ~8a ~8@a\n"
521 "% " "cumulative" "self" "" "self" "total" "")
522 (format port "~5a ~9a ~8a ~8a ~8a ~8a ~8@a\n"
523 "time" "seconds" "seconds" "calls" "ms/call" "ms/call" "name"))
524 (begin
525 (format port "~5a ~10a ~7a ~8@a\n"
526 "%" "cumulative" "self" "")
527 (format port "~5a ~10a ~7a ~8@a\n"
528 "time" "seconds" "seconds" "name")))
529
530 (for-each display-stats-line sorted-stats)
531
532 (display "---\n" port)
533 (simple-format #t "Sample count: ~A\n" (statprof-sample-count))
534 (simple-format #t "Total time: ~A seconds (~A seconds in GC)\n"
535 (statprof-accumulated-time)
536 (/ gc-time-taken 1.0 internal-time-units-per-second))))))
537
538 (define (statprof-display-anomolies)
539 "A sanity check that attempts to detect anomolies in statprof's
540 statistics.@code{}"
541 (statprof-fold-call-data
542 (lambda (data prior-value)
543 (if (and %count-calls?
544 (zero? (call-data-call-count data))
545 (positive? (call-data-cum-sample-count data)))
546 (simple-format #t
547 "==[~A ~A ~A]\n"
548 (call-data-name data)
549 (call-data-call-count data)
550 (call-data-cum-sample-count data))))
551 #f)
552 (simple-format #t "Total time: ~A\n" (statprof-accumulated-time))
553 (simple-format #t "Sample count: ~A\n" (statprof-sample-count)))
554
555 (define (statprof-accumulated-time)
556 "Returns the time accumulated during the last statprof run.@code{}"
557 (if (positive? profile-level)
558 (error "Can't get accumulated time while profiler is running."))
559 (/ accumulated-time internal-time-units-per-second))
560
561 (define (statprof-sample-count)
562 "Returns the number of samples taken during the last statprof run.@code{}"
563 (if (positive? profile-level)
564 (error "Can't get accumulated time while profiler is running."))
565 sample-count)
566
567 (define statprof-call-data-name call-data-name)
568 (define statprof-call-data-calls call-data-call-count)
569 (define statprof-call-data-cum-samples call-data-cum-sample-count)
570 (define statprof-call-data-self-samples call-data-self-sample-count)
571
572 (define (statprof-fetch-stacks)
573 "Returns a list of stacks, as they were captured since the last call
574 to @code{statprof-reset}.
575
576 Note that stacks are only collected if the @var{full-stacks?} argument
577 to @code{statprof-reset} is true."
578 stacks)
579
580 (define procedure=?
581 (lambda (a b)
582 (cond
583 ((eq? a b))
584 ((and (program? a) (program? b))
585 (eq? (program-objcode a) (program-objcode b)))
586 (else
587 #f))))
588
589 ;; tree ::= (car n . tree*)
590
591 (define (lists->trees lists equal?)
592 (let lp ((in lists) (n-terminal 0) (tails '()))
593 (cond
594 ((null? in)
595 (let ((trees (map (lambda (tail)
596 (cons (car tail)
597 (lists->trees (cdr tail) equal?)))
598 tails)))
599 (cons (apply + n-terminal (map cadr trees))
600 (sort trees
601 (lambda (a b) (> (cadr a) (cadr b)))))))
602 ((null? (car in))
603 (lp (cdr in) (1+ n-terminal) tails))
604 ((find (lambda (x) (equal? (car x) (caar in)))
605 tails)
606 => (lambda (tail)
607 (lp (cdr in)
608 n-terminal
609 (assq-set! tails
610 (car tail)
611 (cons (cdar in) (cdr tail))))))
612 (else
613 (lp (cdr in)
614 n-terminal
615 (acons (caar in) (list (cdar in)) tails))))))
616
617 (define (stack->procedures stack)
618 (filter identity
619 (unfold-right (lambda (x) (not x))
620 frame-procedure
621 frame-previous
622 (stack-ref stack 0))))
623
624 (define (statprof-fetch-call-tree)
625 "Return a call tree for the previous statprof run.
626
627 The return value is a list of nodes, each of which is of the type:
628 @code
629 node ::= (@var{proc} @var{count} . @var{nodes})
630 @end code"
631 (cons #t (lists->trees (map stack->procedures stacks) procedure=?)))
632
633 (define* (statprof thunk #:key (loop 1) (hz 100) (count-calls? #f)
634 (full-stacks? #f))
635 "Profiles the execution of @var{thunk}.
636
637 The stack will be sampled @var{hz} times per second, and the thunk itself will
638 be called @var{loop} times.
639
640 If @var{count-calls?} is true, all procedure calls will be recorded. This
641 operation is somewhat expensive.
642
643 If @var{full-stacks?} is true, at each sample, statprof will store away the
644 whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
645 @code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
646
647 (dynamic-wind
648 (lambda ()
649 (statprof-reset (inexact->exact (floor (/ 1 hz)))
650 (inexact->exact (* 1e6 (- (/ 1 hz)
651 (floor (/ 1 hz)))))
652 count-calls?
653 full-stacks?)
654 (statprof-start))
655 (lambda ()
656 (let lp ((i loop))
657 (if (not (zero? i))
658 (begin
659 (thunk)
660 (lp (1- i))))))
661 (lambda ()
662 (statprof-stop)
663 (statprof-display)
664 (set! procedure-data #f))))
665
666 (define-macro (with-statprof . args)
667 "Profiles the expressions in its body.
668
669 Keyword arguments:
670
671 @table @code
672 @item #:loop
673 Execute the body @var{loop} number of times, or @code{#f} for no looping
674
675 default: @code{#f}
676 @item #:hz
677 Sampling rate
678
679 default: @code{20}
680 @item #:count-calls?
681 Whether to instrument each function call (expensive)
682
683 default: @code{#f}
684 @item #:full-stacks?
685 Whether to collect away all sampled stacks into a list
686
687 default: @code{#f}
688 @end table"
689 (define (kw-arg-ref kw args def)
690 (cond
691 ((null? args) (error "Invalid macro body"))
692 ((keyword? (car args))
693 (if (eq? (car args) kw)
694 (cadr args)
695 (kw-arg-ref kw (cddr args) def)))
696 ((eq? kw #f def) ;; asking for the body
697 args)
698 (else def))) ;; kw not found
699 `((@ (statprof) statprof)
700 (lambda () ,@(kw-arg-ref #f args #f))
701 #:loop ,(kw-arg-ref #:loop args 1)
702 #:hz ,(kw-arg-ref #:hz args 100)
703 #:count-calls? ,(kw-arg-ref #:count-calls? args #f)
704 #:full-stacks? ,(kw-arg-ref #:full-stacks? args #f)))
705
706 (define* (gcprof thunk #:key (loop 1) (full-stacks? #f))
707 "Do an allocation profile of the execution of @var{thunk}.
708
709 The stack will be sampled soon after every garbage collection, yielding
710 an approximate idea of what is causing allocation in your program.
711
712 Since GC does not occur very frequently, you may need to use the
713 @var{loop} parameter, to cause @var{thunk} to be called @var{loop}
714 times.
715
716 If @var{full-stacks?} is true, at each sample, statprof will store away the
717 whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
718 @code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
719
720 (define (reset)
721 (if (positive? profile-level)
722 (error "Can't reset profiler while profiler is running."))
723 (set! accumulated-time 0)
724 (set! last-start-time #f)
725 (set! sample-count 0)
726 (set! %count-calls? #f)
727 (set! procedure-data (make-hash-table 131))
728 (set! record-full-stacks? full-stacks?)
729 (set! stacks '()))
730
731 (define (gc-callback)
732 (cond
733 (inside-profiler?)
734 (else
735 (set! inside-profiler? #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 stack)
745 (accumulate-time stop-time)
746 (set! last-start-time (get-internal-run-time)))
747
748 (set! inside-profiler? #f))))
749
750 (define (start)
751 (set! profile-level (+ profile-level 1))
752 (if (= profile-level 1)
753 (begin
754 (set! remaining-prof-time #f)
755 (set! last-start-time (get-internal-run-time))
756 (set! gc-time-taken (cdr (assq 'gc-time-taken (gc-stats))))
757 (add-hook! after-gc-hook gc-callback)
758 (set-vm-trace-level! (the-vm) (1+ (vm-trace-level (the-vm))))
759 #t)))
760
761 (define (stop)
762 (set! profile-level (- profile-level 1))
763 (if (zero? profile-level)
764 (begin
765 (set! gc-time-taken
766 (- (cdr (assq 'gc-time-taken (gc-stats))) gc-time-taken))
767 (remove-hook! after-gc-hook gc-callback)
768 (accumulate-time (get-internal-run-time))
769 (set! last-start-time #f))))
770
771 (dynamic-wind
772 (lambda ()
773 (reset)
774 (start))
775 (lambda ()
776 (let lp ((i loop))
777 (if (not (zero? i))
778 (begin
779 (thunk)
780 (lp (1- i))))))
781 (lambda ()
782 (stop)
783 (statprof-display)
784 (set! procedure-data #f))))