1 (define-module (scm memory-trace))
3 (use-modules (ice-9 format))
4 (define-public (mtrace:start-trace freq)
5 (set! usecond-interval (inexact->exact (/ 1000000 freq)))
6 (call-with-new-thread start-install-tracepoint))
8 (define-public (mtrace:stop-trace)
9 (set! continue-tracing #f))
11 (define-public mtrace:trace-depth 12)
13 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
15 (define trace-points '())
16 (define continue-tracing #t)
17 (define busy-tracing #f)
18 (define trace-thread #f)
20 (define trace-count 0)
21 (define usecond-interval 100000)
22 (define (arg-procedure args)
28 (define (record-stack key continuation . args)
29 (if (eq? (current-thread) trace-thread)
32 (set! busy-tracing #t)
34 (trap-disable 'enter-frame)
35 (set! trace-count (1+ trace-count))
39 (assoc 'total-cells-allocated (gc-stats))
40 (cons 'stack (extract-trace continuation))
41 (cons 'proc (arg-procedure args))
46 (set! busy-tracing #f))))
48 (define (start-install-tracepoint)
49 (set! trace-thread (current-thread))
52 (define (install-tracepoint)
54 (display "last trace not finished yet\n" (current-error-port))
56 (trap-set! enter-frame-handler record-stack)
57 (trap-enable 'enter-frame)
58 (trap-enable 'traps)))
60 (usleep usecond-interval)
62 (install-tracepoint)))
64 (define-public (mtrace:dump-results base)
65 (define out (open-output-file (format #f "~a.graph" base)))
66 (define stacks-out (open-output-file (format #f "~a.stacks" base)))
69 (format out "# memory trace with ~a points\n" (length trace-points))
74 ((mem (cdr (assoc 'total-cells-allocated r)))
75 (proc (cdr (assoc 'proc r)))
76 (stack (cdr (assoc 'stack r))))
78 (format out "~a ~a\n" i mem)
81 (format stacks-out "~15a - delta-mem: ~15a - ~a \n" i
82 (- mem last-mem) proc)
85 (stack (cdr (assoc 'stack r)) stack))
86 ((>= j (vector-length stack)))
88 (format stacks-out "\t~a\n"
89 (vector-ref stack j)))))
94 (reverse trace-points)))
98 (define (test-graph . rest)
99 (mtrace:start-trace 100)
102 (mtrace:dump-results "test"))
106 (define (extract-trace continuation)
108 ((stack (make-stack continuation))
109 (depth (min (stack-length stack) mtrace:trace-depth))
110 (trace (make-vector depth #f)))
119 ((source (frame-source (stack-ref stack i))))
122 (cons (source-property source 'filename)
123 (source-property source 'line))))))