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 (set! busy-tracing #t)
37 (trap-disable 'enter-frame)
39 (set! trace-count (1+ trace-count))
40 (ly:progress "<~a: ~a>\n"
42 (- (cdr (assoc 'total-cells-allocated (gc-stats))) last-count))
43 (set! last-count (cdr (assoc 'total-cells-allocated (gc-stats))))
46 (assoc 'total-cells-allocated (gc-stats))
47 (cons 'stack (extract-trace continuation))
48 (cons 'proc (arg-procedure args))
49 (cons 'time (tms:utime (times)))
54 (set! busy-tracing #f))))
56 (define (start-install-tracepoint)
57 (set! trace-thread (current-thread))
58 (set! trace-points '())
59 (set! continue-tracing #t)
61 (set! start-memory (cdr (assoc 'total-cells-allocated (gc-stats))))
62 (set! start-time (tms:utime (times)))
66 (define (install-tracepoint)
68 (display "last trace not finished yet\n" (current-error-port))
70 (trap-set! enter-frame-handler record-stack)
71 (trap-enable 'enter-frame)
72 (trap-enable 'traps)))
74 (usleep usecond-interval)
76 (install-tracepoint)))
78 (define-public (mtrace:dump-results base)
80 ((stacks-name (format #f "~a.stacks" base))
81 (graph-name (format #f "~a.graph" base))
82 (graph-out (open-output-file graph-name))
83 (stacks-out (open-output-file stacks-name))
88 (ly:progress "Memory statistics to ~a and ~a..."
89 stacks-name graph-name)
90 (format graph-out "# memory trace with ~a points\n" (length trace-points))
94 ((mem (- (cdr (assoc 'total-cells-allocated r)) start-memory))
95 (proc (cdr (assoc 'proc r)))
96 (stack (cdr (assoc 'stack r)))
97 (time (- (cdr (assoc 'time r)) start-time)))
99 (format graph-out "~a ~a\n" time mem)
102 (format stacks-out "~5a t = ~5a - delta-mem: ~15a - ~a \n" i
104 (- mem last-mem) proc)
107 (stack (cdr (assoc 'stack r)) stack))
108 ((>= j (vector-length stack)))
110 (format stacks-out "\t~a\n"
111 (vector-ref stack j)))))
116 (reverse trace-points))))
119 (define (test-graph . rest)
120 (mtrace:start-trace 100)
123 (mtrace:dump-results "test"))
127 (define (extract-trace continuation)
129 ((stack (make-stack continuation))
130 (depth (min (stack-length stack) mtrace:trace-depth))
131 (trace (make-vector depth #f)))
140 ((source (frame-source (stack-ref stack i))))
143 (cons (source-property source 'filename)
144 (source-property source 'line))))))