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