Statprof commentings
[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)
3f9f4a2d 115 #:use-module (system vm debug)
e1138ba1 116 #:use-module (system vm program)
47f3ce52
AW
117 #:export (statprof-active?
118 statprof-start
119 statprof-stop
120 statprof-reset
121
122 statprof-accumulated-time
123 statprof-sample-count
124 statprof-fold-call-data
125 statprof-proc-call-data
126 statprof-call-data-name
127 statprof-call-data-calls
128 statprof-call-data-cum-samples
129 statprof-call-data-self-samples
130 statprof-call-data->stats
131
132 statprof-stats-proc-name
ee3f9604 133 statprof-stats-proc-source
47f3ce52
AW
134 statprof-stats-%-time-in-proc
135 statprof-stats-cum-secs-in-proc
136 statprof-stats-self-secs-in-proc
137 statprof-stats-calls
138 statprof-stats-self-secs-per-call
139 statprof-stats-cum-secs-per-call
140
141 statprof-display
91db6c4f
AW
142 statprof-display-anomalies
143 statprof-display-anomolies ; Deprecated spelling.
47f3ce52
AW
144
145 statprof-fetch-stacks
146 statprof-fetch-call-tree
147
e1138ba1 148 statprof
2d239a78
AW
149 with-statprof
150
151 gcprof))
47f3ce52
AW
152
153
1145f406
AW
154;;; ~ Implementation notes ~
155;;;
156;;; Statprof can be divided into two pieces: data collection and data
157;;; analysis.
158;;;
159;;; The data collection runs concurrently with the program, and is
160;;; designed to be as cheap as possible. The main data collection
161;;; instrument is the stack sampler, driven by SIGPROF signals that are
162;;; scheduled with periodic setitimer calls. The stack sampler simply
163;;; looks at every frame on the stack, and writes a representation of
164;;; the frame's procedure into a growable buffer.
165;;;
166;;; For most frames, this representation is the instruction pointer of
167;;; that frame, because it's cheap to get and you can map from
168;;; instruction pointer to procedure fairly cheaply. This won't
169;;; distinguish between different closures which share the same code,
170;;; but that is usually what we want anyway.
171;;;
172;;; One case in which we do want to distinguish closures is the case of
173;;; primitive procedures. If slot 0 in the frame is a primitive
174;;; procedure, we record the procedure's name into the buffer instead of
175;;; the IP. It's fairly cheap to check whether a value is a primitive
176;;; procedure, and then get its name, as its name is stored in the
177;;; closure data. Calling procedure-name in the stack sampler isn't
178;;; something you want to do for other kinds of procedures, though, as
179;;; that involves grovelling the debug information.
180;;;
181;;; The other part of data collection is the exact call counter, which
182;;; uses the VM's "apply" hook to record each procedure call.
183;;; Naturally, this is quite expensive, and it is off by default.
184;;; Running code at every procedure call effectively penalizes procedure
185;;; calls. Still, it's useful sometimes. If the profiler state has a
186;;; call-counts table, then calls will be counted. As with the stack
187;;; counter, usually the key in the hash table is the code pointer of
188;;; the procedure being called, except for primitive procedures, in
189;;; which case it is the name of the primitive. The call counter can
190;;; also see calls of non-programs, for example in the case of
191;;; applicable structs. In that case the key is the procedure itself.
192;;;
193;;; After collection is finished, the data can be analyzed. The first
194;;; step is usually to run over the stack traces, tabulating sample
195;;; counts by procedure; the stack-samples->procedure-data does that.
196;;; The result of stack-samples->procedure-data is a hash table mapping
197;;; procedures to "call data" records. The call data values are exposed
198;;; to users via the statprof-fold-call-data procedure.
199;;;
200;;; Usually all the analysis is triggered by calling statprof-display,
201;;; or having the statprof procedure call it for you.
202;;;
203;;; The other thing we can do is to look at the stacks themselves, for
204;;; example via statprof-fetch-call-tree.
205;;;
206
207;;; ~ Threads and state ~
208;;;
209;;; The state of the profiler is contained in a <state> record, which is
210;;; bound to a thread-local parameter. The accurate call counter uses
211;;; the VM apply hook, which is also local to the current thread, so all
212;;; is good there.
213;;;
214;;; The problem comes in the statistical stack sampler's use of
215;;; `setitimer' and SIGPROF. The timer manipulated by setitimer is a
216;;; whole-process timer, so it decrements as other threads execute,
217;;; which is the wrong thing if you want to profile just one thread. On
218;;; the other hand, SIGPROF is delivered to the process as a whole,
219;;; which is fine given Guile's signal-handling thread, but then only
220;;; delivered to the thread running statprof, which isn't the right
221;;; thing if you want to profile the whole system.
222;;;
223;;; The summary is that statprof works more or less well as a per-thread
224;;; profiler if no other threads are running on their own when
225;;; profiling. If the other threads are running on behalf of the thread
226;;; being profiled (as via futures or parallel marking) things still
227;;; mostly work as expected. You can run statprof in one thread,
228;;; finish, and then run statprof in another thread, and the profile
229;;; runs won't affect each other. But if you want true per-thread
230;;; profiles when other things are happening in the process, including
231;;; other statprof runs, or whole-process profiles with per-thread
232;;; breakdowns, the use of setitimer currently prevents that.
233;;;
234;;; The solution would be to switch to POSIX.1-2001's timer_create(2),
235;;; and to add some more threading-related API to statprof. Some other
236;;; day.
237;;;
47f3ce52 238
62fd93e2
AW
239(define-record-type <state>
240 (make-state accumulated-time last-start-time sample-count
19bf8caf 241 sampling-period remaining-prof-time profile-level
cd073eb4 242 call-counts gc-time-taken inside-profiler?
3f9f4a2d 243 prev-sigprof-handler buffer buffer-pos)
62fd93e2
AW
244 state?
245 ;; Total time so far.
246 (accumulated-time accumulated-time set-accumulated-time!)
247 ;; Start-time when timer is active.
248 (last-start-time last-start-time set-last-start-time!)
249 ;; Total count of sampler calls.
250 (sample-count sample-count set-sample-count!)
19bf8caf
AW
251 ;; Microseconds.
252 (sampling-period sampling-period set-sampling-period!)
62fd93e2
AW
253 ;; Time remaining when prof suspended.
254 (remaining-prof-time remaining-prof-time set-remaining-prof-time!)
255 ;; For user start/stop nesting.
256 (profile-level profile-level set-profile-level!)
3f9f4a2d
AW
257 ;; Hash table mapping ip -> call count, or #f if not counting calls.
258 (call-counts call-counts set-call-counts!)
62fd93e2
AW
259 ;; GC time between statprof-start and statprof-stop.
260 (gc-time-taken gc-time-taken set-gc-time-taken!)
56bfce7c 261 ;; True if we are inside the profiler.
3072d762
AW
262 (inside-profiler? inside-profiler? set-inside-profiler?!)
263 ;; True if we are inside the profiler.
3f9f4a2d
AW
264 (prev-sigprof-handler prev-sigprof-handler set-prev-sigprof-handler!)
265 ;; Stack samples.
266 (buffer buffer set-buffer!)
267 (buffer-pos buffer-pos set-buffer-pos!))
62fd93e2
AW
268
269(define profiler-state (make-parameter #f))
270
3f9f4a2d
AW
271(define (fresh-buffer)
272 (make-vector 1024 #f))
273
274(define (expand-buffer buf)
275 (let* ((size (vector-length buf))
276 (new (make-vector (* size 2) #f)))
277 (vector-move-left! buf 0 (vector-length buf) new 0)
278 new))
279
4eb1fb9b 280(define* (fresh-profiler-state #:key (count-calls? #f)
cd073eb4
AW
281 (sampling-period 10000))
282 (make-state 0 #f 0
283 sampling-period 0 0
284 (and count-calls? (make-hash-table)) 0 #f
285 #f (fresh-buffer) 0))
4eb1fb9b 286
62fd93e2
AW
287(define (ensure-profiler-state)
288 (or (profiler-state)
4eb1fb9b 289 (let ((state (fresh-profiler-state)))
62fd93e2
AW
290 (profiler-state state)
291 state)))
47f3ce52 292
45a7de82
AW
293(define (existing-profiler-state)
294 (or (profiler-state)
295 (error "expected there to be a profiler state")))
296
62fd93e2
AW
297(define (accumulate-time state stop-time)
298 (set-accumulated-time! state
299 (+ (accumulated-time state)
62fd93e2 300 (- stop-time (last-start-time state)))))
47f3ce52 301
47f3ce52
AW
302;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
303;; SIGPROF handler
304
e4a8775d 305(define (sample-stack-procs state stack)
3f9f4a2d
AW
306 (set-sample-count! state (+ (sample-count state) 1))
307
308 (let lp ((frame (stack-ref stack 0))
309 (buffer (buffer state))
310 (pos (buffer-pos state)))
311 (define (write-sample sample)
312 (vector-set! buffer pos sample))
313 (define (continue pos)
314 (lp (frame-previous frame) buffer pos))
315 (define (write-sample-and-continue sample)
316 (write-sample sample)
317 (continue (1+ pos)))
318 (cond
319 ((= pos (vector-length buffer))
320 (lp frame (expand-buffer buffer) pos))
321 ((not frame)
322 (write-sample #f)
323 (set-buffer! state buffer)
324 (set-buffer-pos! state (1+ pos)))
325 (else
326 (let ((proc (frame-procedure frame)))
1145f406
AW
327 (write-sample-and-continue (if (primitive? proc)
328 (procedure-name proc)
329 (frame-instruction-pointer frame))))))))
47f3ce52 330
19bf8caf 331(define (reset-sigprof-timer usecs)
e68ed839
AW
332 ;; Guile's setitimer binding is terrible.
333 (let ((prev (setitimer ITIMER_PROF 0 0 0 usecs)))
334 (+ (* (caadr prev) #e1e6) (cdadr prev))))
19bf8caf 335
47f3ce52 336(define (profile-signal-handler sig)
45a7de82 337 (define state (existing-profiler-state))
62fd93e2 338
56bfce7c 339 (set-inside-profiler?! state #t)
47f3ce52
AW
340
341 ;; FIXME: with-statprof should be able to set an outer frame for the
342 ;; stack cut
cad444e3
AW
343 (when (positive? (profile-level state))
344 (let* ((stop-time (get-internal-run-time))
345 ;; cut down to the signal handler. note that this will only
346 ;; work if statprof.scm is compiled; otherwise we get
347 ;; `eval' on the stack instead, because if it's not
348 ;; compiled, profile-signal-handler is a thunk that
349 ;; tail-calls eval. perhaps we should always compile the
350 ;; signal handler instead...
351 (stack (or (make-stack #t profile-signal-handler)
546efe25
AW
352 (pk 'what! (make-stack #t)))))
353
354 (sample-stack-procs state stack)
355 (accumulate-time state stop-time)
356 (set-last-start-time! state (get-internal-run-time))
357
19bf8caf 358 (reset-sigprof-timer (sampling-period state))))
e1138ba1 359
56bfce7c 360 (set-inside-profiler?! state #f))
47f3ce52
AW
361
362;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
363;; Count total calls.
364
e1138ba1 365(define (count-call frame)
3f9f4a2d
AW
366 (let ((state (existing-profiler-state)))
367 (unless (inside-profiler? state)
368 (accumulate-time state (get-internal-run-time))
62fd93e2 369
3f9f4a2d
AW
370 (let* ((key (let ((proc (frame-procedure frame)))
371 (cond
372 ((primitive? proc) (procedure-name proc))
373 ((program? proc) (program-code proc))
374 (else proc))))
375 (handle (hashv-create-handle! (call-counts state) key 0)))
376 (set-cdr! handle (1+ (cdr handle))))
47f3ce52 377
3f9f4a2d 378 (set-last-start-time! state (get-internal-run-time)))))
47f3ce52
AW
379
380;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
381
382(define (statprof-active?)
383 "Returns @code{#t} if @code{statprof-start} has been called more times
384than @code{statprof-stop}, @code{#f} otherwise."
45a7de82
AW
385 (define state (profiler-state))
386 (and state (positive? (profile-level state))))
47f3ce52
AW
387
388;; Do not call this from statprof internal functions -- user only.
13a977dd 389(define* (statprof-start #:optional (state (ensure-profiler-state)))
47f3ce52
AW
390 "Start the profiler.@code{}"
391 ;; After some head-scratching, I don't *think* I need to mask/unmask
392 ;; signals here, but if I'm wrong, please let me know.
62fd93e2 393 (set-profile-level! state (+ (profile-level state) 1))
cad444e3 394 (when (= (profile-level state) 1)
19bf8caf
AW
395 (let ((rpt (remaining-prof-time state)))
396 (set-remaining-prof-time! state 0)
cad444e3
AW
397 ;; FIXME: Use per-thread run time.
398 (set-last-start-time! state (get-internal-run-time))
3476a369 399 (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
3072d762
AW
400 (let ((prev (sigaction SIGPROF profile-signal-handler)))
401 (set-prev-sigprof-handler! state (car prev)))
19bf8caf 402 (reset-sigprof-timer (if (zero? rpt) (sampling-period state) rpt))
3f9f4a2d 403 (when (call-counts state)
cad444e3
AW
404 (add-hook! (vm-apply-hook) count-call))
405 (set-vm-trace-level! (1+ (vm-trace-level)))
406 #t)))
47f3ce52
AW
407
408;; Do not call this from statprof internal functions -- user only.
13a977dd 409(define* (statprof-stop #:optional (state (ensure-profiler-state)))
47f3ce52
AW
410 "Stop the profiler.@code{}"
411 ;; After some head-scratching, I don't *think* I need to mask/unmask
412 ;; signals here, but if I'm wrong, please let me know.
62fd93e2 413 (set-profile-level! state (- (profile-level state) 1))
cad444e3
AW
414 (when (zero? (profile-level state))
415 (set-gc-time-taken! state
3476a369 416 (- (assq-ref (gc-stats) 'gc-time-taken)
cad444e3
AW
417 (gc-time-taken state)))
418 (set-vm-trace-level! (1- (vm-trace-level)))
3f9f4a2d 419 (when (call-counts state)
cad444e3
AW
420 (remove-hook! (vm-apply-hook) count-call))
421 ;; I believe that we need to do this before getting the time
422 ;; (unless we want to make things even more complicated).
19bf8caf 423 (set-remaining-prof-time! state (reset-sigprof-timer 0))
cad444e3 424 (accumulate-time state (get-internal-run-time))
3072d762
AW
425 (sigaction SIGPROF (prev-sigprof-handler state))
426 (set-prev-sigprof-handler! state #f)
cad444e3 427 (set-last-start-time! state #f)))
47f3ce52 428
e640b440
AW
429(define* (statprof-reset sample-seconds sample-microseconds count-calls?
430 #:optional full-stacks?)
47f3ce52
AW
431 "Reset the statprof sampler interval to @var{sample-seconds} and
432@var{sample-microseconds}. If @var{count-calls?} is true, arrange to
433instrument procedure calls as well as collecting statistical profiling
cd073eb4
AW
434data. (The optional @var{full-stacks?} argument is deprecated; statprof
435always collects full stacks.)"
4d0c358b 436 (when (statprof-active?)
4eb1fb9b 437 (error "Can't reset profiler while profiler is running."))
3072d762
AW
438 (profiler-state
439 (fresh-profiler-state #:count-calls? count-calls?
440 #:sampling-period (+ (* sample-seconds #e1e6)
cd073eb4 441 sample-microseconds)))
13a977dd 442 (values))
47f3ce52 443
3f9f4a2d 444(define-record-type call-data
ee3f9604 445 (make-call-data name printable source
e3997e70 446 call-count cum-sample-count self-sample-count)
3f9f4a2d
AW
447 call-data?
448 (name call-data-name)
449 (printable call-data-printable)
ee3f9604 450 (source call-data-source)
3f9f4a2d
AW
451 (call-count call-data-call-count set-call-data-call-count!)
452 (cum-sample-count call-data-cum-sample-count set-call-data-cum-sample-count!)
453 (self-sample-count call-data-self-sample-count set-call-data-self-sample-count!))
454
455(define (source->string source)
456 (format #f "~a:~a:~a"
457 (or (source-file source) "<current input>")
458 (source-line-for-user source)
459 (source-column source)))
460
461(define (program-debug-info-printable pdi)
462 (let* ((addr (program-debug-info-addr pdi))
463 (name (or (and=> (program-debug-info-name pdi) symbol->string)
464 (string-append "#x" (number->string addr 16))))
465 (loc (and=> (find-source-for-addr addr) source->string)))
466 (if loc
467 (string-append name " at " loc)
468 name)))
469
470(define (addr->pdi addr cache)
471 (cond
472 ((hashv-get-handle cache addr) => cdr)
473 (else
474 (let ((data (find-program-debug-info addr)))
475 (hashv-set! cache addr data)
476 data))))
477
478(define (addr->printable addr pdi)
ee3f9604
AW
479 (or (and=> (and=> pdi program-debug-info-name) symbol->string)
480 (string-append "anon #x" (number->string addr 16))))
3f9f4a2d
AW
481
482(define (inc-call-data-cum-sample-count! cd)
483 (set-call-data-cum-sample-count! cd (1+ (call-data-cum-sample-count cd))))
484(define (inc-call-data-self-sample-count! cd)
485 (set-call-data-self-sample-count! cd (1+ (call-data-self-sample-count cd))))
486
487(define (stack-samples->procedure-data state)
488 (let ((table (make-hash-table))
489 (addr-cache (make-hash-table))
490 (call-counts (call-counts state))
491 (buffer (buffer state))
492 (len (buffer-pos state)))
493 (define (addr->call-data addr)
494 (let* ((pdi (addr->pdi addr addr-cache))
495 (entry (if pdi (program-debug-info-addr pdi) addr)))
496 (or (hashv-ref table entry)
497 (let ((data (make-call-data (and=> pdi program-debug-info-name)
498 (addr->printable entry pdi)
ee3f9604 499 (find-source-for-addr entry)
3f9f4a2d
AW
500 (and call-counts
501 (hashv-ref call-counts entry))
502 0
503 0)))
504 (hashv-set! table entry data)
505 data))))
506
507 (define (callee->call-data callee)
508 (cond
509 ((number? callee) (addr->call-data callee))
510 ((hashv-ref table callee))
511 (else
512 (let ((data (make-call-data
513 (cond ((procedure? callee) (procedure-name callee))
514 ;; a primitive
515 ((symbol? callee) callee)
516 (else #f))
517 (with-output-to-string (lambda () (write callee)))
ee3f9604 518 #f
3f9f4a2d
AW
519 (and call-counts (hashv-ref call-counts callee))
520 0
521 0)))
522 (hashv-set! table callee data)
523 data))))
524
525 (when call-counts
526 (hash-for-each (lambda (callee count)
527 (callee->call-data callee))
528 call-counts))
529
530 (let visit-stacks ((pos 0))
531 (cond
532 ((< pos len)
533 ;; FIXME: if we are counting all procedure calls, and
534 ;; count-call is on the stack, we need to not count the part
535 ;; of the stack that is within count-call.
536 (inc-call-data-self-sample-count!
537 (callee->call-data (vector-ref buffer pos)))
538 (let visit-stack ((pos pos))
cd073eb4
AW
539 (cond
540 ((vector-ref buffer pos)
541 => (lambda (callee)
542 (inc-call-data-cum-sample-count! (callee->call-data callee))
543 (visit-stack (1+ pos))))
544 (else
545 (visit-stacks (1+ pos))))))
3f9f4a2d
AW
546 (else table)))))
547
cd073eb4
AW
548(define (stack-samples->callee-lists state)
549 (let ((buffer (buffer state))
550 (len (buffer-pos state)))
551 (let visit-stacks ((pos 0) (out '()))
552 (cond
553 ((< pos len)
554 ;; FIXME: if we are counting all procedure calls, and
555 ;; count-call is on the stack, we need to not count the part
556 ;; of the stack that is within count-call.
557 (let visit-stack ((pos pos) (stack '()))
558 (cond
559 ((vector-ref buffer pos)
560 => (lambda (callee)
561 (visit-stack (1+ pos) (cons callee stack))))
562 (else
563 (visit-stacks (1+ pos) (cons (reverse stack) out))))))
564 (else (reverse out))))))
565
47f3ce52
AW
566(define (statprof-fold-call-data proc init)
567 "Fold @var{proc} over the call-data accumulated by statprof. Cannot be
568called while statprof is active. @var{proc} should take two arguments,
569@code{(@var{call-data} @var{prior-result})}.
570
571Note that a given proc-name may appear multiple times, but if it does,
572it represents different functions with the same name."
4d0c358b
AW
573 (when (statprof-active?)
574 (error "Can't call statprof-fold-call-data while profiler is running."))
47f3ce52
AW
575 (hash-fold
576 (lambda (key value prior-result)
577 (proc value prior-result))
578 init
3f9f4a2d 579 (stack-samples->procedure-data (existing-profiler-state))))
47f3ce52
AW
580
581(define (statprof-proc-call-data proc)
582 "Returns the call-data associated with @var{proc}, or @code{#f} if
583none is available."
4d0c358b
AW
584 (when (statprof-active?)
585 (error "Can't call statprof-proc-call-data while profiler is running."))
3f9f4a2d
AW
586 (hashv-ref (stack-samples->procedure-data (existing-profiler-state))
587 (cond
588 ((primitive? proc) (procedure-name proc))
589 ((program? proc) (program-code proc))
590 (else (program-code proc)))))
47f3ce52
AW
591
592;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
593;; Stats
594
e3997e70 595(define-record-type stats
ee3f9604
AW
596 (make-stats proc-name proc-source
597 %-time-in-proc cum-secs-in-proc self-secs-in-proc
e3997e70
AW
598 calls self-secs-per-call cum-secs-per-call)
599 stats?
600 (proc-name statprof-stats-proc-name)
ee3f9604 601 (proc-source statprof-stats-proc-source)
e3997e70
AW
602 (%-time-in-proc statprof-stats-%-time-in-proc)
603 (cum-secs-in-proc statprof-stats-cum-secs-in-proc)
604 (self-secs-in-proc statprof-stats-self-secs-in-proc)
605 (calls statprof-stats-calls)
606 (self-secs-per-call statprof-stats-self-secs-per-call)
607 (cum-secs-per-call statprof-stats-cum-secs-per-call))
608
47f3ce52
AW
609(define (statprof-call-data->stats call-data)
610 "Returns an object of type @code{statprof-stats}."
45a7de82 611 (define state (existing-profiler-state))
62fd93e2 612
ee3f9604
AW
613 (let* ((proc-name (call-data-name call-data))
614 (proc-source (and=> (call-data-source call-data) source->string))
47f3ce52
AW
615 (self-samples (call-data-self-sample-count call-data))
616 (cum-samples (call-data-cum-sample-count call-data))
617 (all-samples (statprof-sample-count))
618 (secs-per-sample (/ (statprof-accumulated-time)
619 (statprof-sample-count)))
3f9f4a2d
AW
620 (num-calls (and (call-counts state)
621 (statprof-call-data-calls call-data))))
47f3ce52 622
ee3f9604
AW
623 (make-stats (or proc-name
624 ;; If there is no name and no source, fall back to
625 ;; printable.
626 (and (not proc-source) (call-data-printable call-data)))
627 proc-source
e3997e70
AW
628 (* (/ self-samples all-samples) 100.0)
629 (* cum-samples secs-per-sample 1.0)
630 (* self-samples secs-per-sample 1.0)
631 num-calls
632 (and num-calls ;; maybe we only sampled in children
633 (if (zero? self-samples) 0.0
634 (/ (* self-samples secs-per-sample) 1.0 num-calls)))
635 (and num-calls ;; cum-samples must be positive
636 (/ (* cum-samples secs-per-sample)
637 1.0
638 ;; num-calls might be 0 if we entered statprof during the
639 ;; dynamic extent of the call
640 (max num-calls 1))))))
47f3ce52
AW
641
642;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
643
644(define (stats-sorter x y)
645 (let ((diff (- (statprof-stats-self-secs-in-proc x)
646 (statprof-stats-self-secs-in-proc y))))
647 (positive?
648 (if (= diff 0)
649 (- (statprof-stats-cum-secs-in-proc x)
650 (statprof-stats-cum-secs-in-proc y))
651 diff))))
652
91db6c4f
AW
653(define* (statprof-display #:optional (port (current-output-port))
654 (state (existing-profiler-state)))
47f3ce52
AW
655 "Displays a gprof-like summary of the statistics collected. Unless an
656optional @var{port} argument is passed, uses the current output port."
47f3ce52
AW
657 (cond
658 ((zero? (statprof-sample-count))
659 (format port "No samples recorded.\n"))
660 (else
661 (let* ((stats-list (statprof-fold-call-data
662 (lambda (data prior-value)
663 (cons (statprof-call-data->stats data)
664 prior-value))
665 '()))
666 (sorted-stats (sort stats-list stats-sorter)))
667
668 (define (display-stats-line stats)
3f9f4a2d
AW
669 (format port "~6,2f ~9,2f ~9,2f"
670 (statprof-stats-%-time-in-proc stats)
671 (statprof-stats-cum-secs-in-proc stats)
672 (statprof-stats-self-secs-in-proc stats))
673 (if (call-counts state)
674 (if (statprof-stats-calls stats)
675 (format port " ~7d ~8,2f ~8,2f "
676 (statprof-stats-calls stats)
677 (* 1000 (statprof-stats-self-secs-per-call stats))
678 (* 1000 (statprof-stats-cum-secs-per-call stats)))
679 (format port " "))
680 (display " " port))
ee3f9604
AW
681 (let ((source (statprof-stats-proc-source stats))
682 (name (statprof-stats-proc-name stats)))
683 (when source
684 (display source port)
685 (when name
686 (display ":" port)))
687 (when name
688 (display name port))
689 (newline port)))
47f3ce52 690
3f9f4a2d 691 (if (call-counts state)
47f3ce52
AW
692 (begin
693 (format port "~5a ~10a ~7a ~8a ~8a ~8a ~8@a\n"
694 "% " "cumulative" "self" "" "self" "total" "")
ee3f9604
AW
695 (format port "~5a ~9a ~8a ~8a ~8a ~8a ~a\n"
696 "time" "seconds" "seconds" "calls" "ms/call" "ms/call" "procedure"))
47f3ce52 697 (begin
ee3f9604 698 (format port "~5a ~10a ~7a ~8a\n"
47f3ce52 699 "%" "cumulative" "self" "")
ee3f9604
AW
700 (format port "~5a ~10a ~7a ~a\n"
701 "time" "seconds" "seconds" "procedure")))
47f3ce52
AW
702
703 (for-each display-stats-line sorted-stats)
704
705 (display "---\n" port)
706 (simple-format #t "Sample count: ~A\n" (statprof-sample-count))
707 (simple-format #t "Total time: ~A seconds (~A seconds in GC)\n"
708 (statprof-accumulated-time)
3476a369
AW
709 (/ (gc-time-taken state)
710 1.0 internal-time-units-per-second))))))
47f3ce52 711
91db6c4f
AW
712(define* (statprof-display-anomalies #:optional (state
713 (existing-profiler-state)))
714 "A sanity check that attempts to detect anomalies in statprof's
47f3ce52
AW
715statistics.@code{}"
716 (statprof-fold-call-data
717 (lambda (data prior-value)
3f9f4a2d 718 (when (and (call-counts state)
cad444e3
AW
719 (zero? (call-data-call-count data))
720 (positive? (call-data-cum-sample-count data)))
721 (simple-format #t
722 "==[~A ~A ~A]\n"
723 (call-data-name data)
724 (call-data-call-count data)
725 (call-data-cum-sample-count data))))
47f3ce52
AW
726 #f)
727 (simple-format #t "Total time: ~A\n" (statprof-accumulated-time))
728 (simple-format #t "Sample count: ~A\n" (statprof-sample-count)))
729
91db6c4f
AW
730(define (statprof-display-anomolies)
731 (issue-deprecation-warning "statprof-display-anomolies is a misspelling. "
732 "Use statprof-display-anomalies instead.")
733 (statprof-display-anomalies))
734
735(define* (statprof-accumulated-time #:optional (state
736 (existing-profiler-state)))
47f3ce52 737 "Returns the time accumulated during the last statprof run.@code{}"
91db6c4f 738 (/ (accumulated-time state) 1.0 internal-time-units-per-second))
47f3ce52 739
91db6c4f 740(define* (statprof-sample-count #:optional (state (existing-profiler-state)))
47f3ce52 741 "Returns the number of samples taken during the last statprof run.@code{}"
91db6c4f 742 (sample-count state))
47f3ce52
AW
743
744(define statprof-call-data-name call-data-name)
745(define statprof-call-data-calls call-data-call-count)
746(define statprof-call-data-cum-samples call-data-cum-sample-count)
747(define statprof-call-data-self-samples call-data-self-sample-count)
748
91db6c4f 749(define* (statprof-fetch-stacks #:optional (state (existing-profiler-state)))
47f3ce52 750 "Returns a list of stacks, as they were captured since the last call
cd073eb4
AW
751to @code{statprof-reset}."
752 (stack-samples->callee-lists state))
47f3ce52
AW
753
754(define procedure=?
663212bb
AW
755 (lambda (a b)
756 (cond
757 ((eq? a b))
0bd1e9c6 758 ((and (program? a) (program? b))
d1100525 759 (eq? (program-code a) (program-code b)))
663212bb
AW
760 (else
761 #f))))
47f3ce52
AW
762
763;; tree ::= (car n . tree*)
764
765(define (lists->trees lists equal?)
766 (let lp ((in lists) (n-terminal 0) (tails '()))
767 (cond
768 ((null? in)
769 (let ((trees (map (lambda (tail)
770 (cons (car tail)
771 (lists->trees (cdr tail) equal?)))
772 tails)))
773 (cons (apply + n-terminal (map cadr trees))
774 (sort trees
775 (lambda (a b) (> (cadr a) (cadr b)))))))
776 ((null? (car in))
777 (lp (cdr in) (1+ n-terminal) tails))
778 ((find (lambda (x) (equal? (car x) (caar in)))
779 tails)
780 => (lambda (tail)
781 (lp (cdr in)
782 n-terminal
783 (assq-set! tails
784 (car tail)
785 (cons (cdar in) (cdr tail))))))
786 (else
787 (lp (cdr in)
788 n-terminal
789 (acons (caar in) (list (cdar in)) tails))))))
790
91db6c4f 791(define* (statprof-fetch-call-tree #:optional (state (existing-profiler-state)))
47f3ce52
AW
792 "Return a call tree for the previous statprof run.
793
794The return value is a list of nodes, each of which is of the type:
795@code
796 node ::= (@var{proc} @var{count} . @var{nodes})
797@end code"
cd073eb4
AW
798 (define (callee->printable callee)
799 (cond
800 ((number? callee)
801 (addr->printable callee (find-program-debug-info callee)))
802 (else
803 (with-output-to-string (lambda () (write callee))))))
804 (define (memoizev/1 proc table)
805 (lambda (x)
806 (cond
807 ((hashv-get-handle table x) => cdr)
808 (else
809 (let ((res (proc x)))
810 (hashv-set! table x res)
811 res)))))
812 (let ((callee->printable (memoizev/1 callee->printable (make-hash-table))))
813 (cons #t (lists->trees (map (lambda (callee-list)
814 (map callee->printable callee-list))
815 (stack-samples->callee-lists state))
816 equal?))))
47f3ce52 817
e1138ba1 818(define* (statprof thunk #:key (loop 1) (hz 100) (count-calls? #f)
cd073eb4 819 (port (current-output-port)) full-stacks?)
e1138ba1
AW
820 "Profiles the execution of @var{thunk}.
821
822The stack will be sampled @var{hz} times per second, and the thunk itself will
823be called @var{loop} times.
824
825If @var{count-calls?} is true, all procedure calls will be recorded. This
cd073eb4 826operation is somewhat expensive."
e1138ba1 827
13a977dd
AW
828 (let ((state (fresh-profiler-state #:count-calls? count-calls?
829 #:sampling-period
cd073eb4 830 (inexact->exact (round (/ 1e6 hz))))))
fd5dfcce
AW
831 (parameterize ((profiler-state state))
832 (dynamic-wind
833 (lambda ()
13a977dd 834 (statprof-start state))
fd5dfcce
AW
835 (lambda ()
836 (let lp ((i loop))
837 (unless (zero? i)
838 (thunk)
839 (lp (1- i)))))
840 (lambda ()
13a977dd
AW
841 (statprof-stop state)
842 (statprof-display port state))))))
e1138ba1 843
47f3ce52
AW
844(define-macro (with-statprof . args)
845 "Profiles the expressions in its body.
846
847Keyword arguments:
848
849@table @code
850@item #:loop
851Execute the body @var{loop} number of times, or @code{#f} for no looping
852
853default: @code{#f}
854@item #:hz
855Sampling rate
856
857default: @code{20}
858@item #:count-calls?
859Whether to instrument each function call (expensive)
860
47f3ce52
AW
861default: @code{#f}
862@end table"
863 (define (kw-arg-ref kw args def)
864 (cond
865 ((null? args) (error "Invalid macro body"))
866 ((keyword? (car args))
867 (if (eq? (car args) kw)
868 (cadr args)
869 (kw-arg-ref kw (cddr args) def)))
870 ((eq? kw #f def) ;; asking for the body
871 args)
872 (else def))) ;; kw not found
e1138ba1
AW
873 `((@ (statprof) statprof)
874 (lambda () ,@(kw-arg-ref #f args #f))
875 #:loop ,(kw-arg-ref #:loop args 1)
876 #:hz ,(kw-arg-ref #:hz args 100)
877 #:count-calls? ,(kw-arg-ref #:count-calls? args #f)
878 #:full-stacks? ,(kw-arg-ref #:full-stacks? args #f)))
879
cd073eb4 880(define* (gcprof thunk #:key (loop 1) full-stacks?)
2d239a78
AW
881 "Do an allocation profile of the execution of @var{thunk}.
882
883The stack will be sampled soon after every garbage collection, yielding
884an approximate idea of what is causing allocation in your program.
885
886Since GC does not occur very frequently, you may need to use the
887@var{loop} parameter, to cause @var{thunk} to be called @var{loop}
cd073eb4 888times."
2d239a78 889
cd073eb4 890 (let ((state (fresh-profiler-state)))
fd5dfcce 891 (parameterize ((profiler-state state))
fd5dfcce 892 (define (gc-callback)
a7ede58d 893 (unless (inside-profiler? state)
fd5dfcce
AW
894 (set-inside-profiler?! state #t)
895
896 ;; FIXME: should be able to set an outer frame for the stack cut
897 (let ((stop-time (get-internal-run-time))
898 ;; Cut down to gc-callback, and then one before (the
899 ;; after-gc async). See the note in profile-signal-handler
900 ;; also.
901 (stack (or (make-stack #t gc-callback 0 1)
902 (pk 'what! (make-stack #t)))))
903 (sample-stack-procs state stack)
904 (accumulate-time state stop-time)
905 (set-last-start-time! state (get-internal-run-time)))
cd073eb4 906
a7ede58d 907 (set-inside-profiler?! state #f)))
fd5dfcce
AW
908
909 (dynamic-wind
910 (lambda ()
a7ede58d
AW
911 (set-profile-level! state 1)
912 (set-last-start-time! state (get-internal-run-time))
913 (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
914 (add-hook! after-gc-hook gc-callback))
fd5dfcce
AW
915 (lambda ()
916 (let lp ((i loop))
917 (unless (zero? i)
918 (thunk)
919 (lp (1- i)))))
920 (lambda ()
a7ede58d
AW
921 (remove-hook! after-gc-hook gc-callback)
922 (set-gc-time-taken! state
923 (- (assq-ref (gc-stats) 'gc-time-taken)
924 (gc-time-taken state)))
925 (accumulate-time state (get-internal-run-time))
926 (set-profile-level! state 0)
fd5dfcce 927 (statprof-display))))))