1 (define-module (scm memory-trace))
5 (define-public (mtrace:start-trace freq)
6 (set! usecond-interval (inexact->exact (/ 1000000 freq)))
7 (call-with-new-thread start-install-tracepoint))
9 (define-public (mtrace:stop-trace)
10 (set! continue-tracing #f))
12 (define-public mtrace:trace-depth 12)
14 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
16 (define trace-points '())
17 (define continue-tracing #t)
18 (define busy-tracing #f)
19 (define trace-thread #f)
21 (define start-memory 0)
23 (define trace-count 0)
24 (define usecond-interval 100000)
25 (define (arg-procedure args)
31 (define (record-stack key continuation . args)
32 (if (eq? (current-thread) trace-thread)
35 ((cells (cdr (assoc 'total-cells-allocated (gc-stats))))
36 (proc (arg-procedure args))
37 (time (tms:utime (times)))
38 (stack (extract-trace continuation)))
40 (set! busy-tracing #t)
42 (trap-disable 'enter-frame)
44 (set! trace-count (1+ trace-count))
45 (ly:progress "<~a: ~a/~a>\n"
50 (set! last-count cells)
61 (set! busy-tracing #f))))
63 (define (start-install-tracepoint)
64 (set! trace-thread (current-thread))
65 (set! trace-points '())
66 (set! continue-tracing #t)
68 (set! start-memory (cdr (assoc 'total-cells-allocated (gc-stats))))
69 (set! start-time (tms:utime (times)))
73 (define (install-tracepoint)
75 (display "last trace not finished yet\n" (current-error-port))
77 (trap-set! enter-frame-handler record-stack)
78 (trap-enable 'enter-frame)
79 (trap-enable 'traps)))
81 (usleep usecond-interval)
83 (install-tracepoint)))
85 (define-public (mtrace:dump-results base)
87 ((stacks-name (format #f "~a.stacks" base))
88 (graph-name (format #f "~a.graph" base))
89 (graph-out (open-output-file graph-name))
90 (stacks-out (open-output-file stacks-name))
95 (ly:progress "Memory statistics to ~a and ~a..."
96 stacks-name graph-name)
97 (format graph-out "# memory trace with ~a points\n" (length trace-points))
101 ((mem (- (cdr (assoc 'cells r)) start-memory))
102 (proc (cdr (assoc 'proc r)))
103 (stack (cdr (assoc 'stack r)))
104 (time (- (cdr (assoc 'time r)) start-time)))
106 (format graph-out "~a ~a\n" time mem)
109 (format stacks-out "~5a t = ~5a - delta-mem: ~15a - ~a\n" i
111 (- mem last-mem) proc)
114 (stack (cdr (assoc 'stack r)) stack))
115 ((>= j (vector-length stack)))
117 (format stacks-out "\t~a\n"
118 (vector-ref stack j)))))
123 (reverse trace-points))))
126 (define (test-graph . rest)
127 (mtrace:start-trace 100)
130 (mtrace:dump-results "test"))
134 (define (extract-trace continuation)
136 ((stack (make-stack continuation))
137 (depth (min (stack-length stack) mtrace:trace-depth))
138 (trace (make-vector depth #f)))
147 ((source (frame-source (stack-ref stack i))))
150 (cons (source-property source 'filename)
151 (source-property source 'line))))))