1 (define-module (scm memory-trace))
3 (define-public (mtrace:start-trace freq)
4 (set! usecond-interval (inexact->exact (/ 1000000 freq)))
5 (call-with-new-thread start-install-tracepoint))
7 (define-public (mtrace:stop-trace)
8 (set! continue-tracing #f))
10 (define-public mtrace:trace-depth 12)
12 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
14 (define trace-points '())
15 (define continue-tracing #t)
16 (define busy-tracing #f)
17 (define trace-thread #f)
19 (define trace-count 0)
20 (define usecond-interval 100000)
21 (define (arg-procedure args)
27 (define (record-stack key continuation . args)
28 (if (eq? (current-thread) trace-thread)
31 (set! busy-tracing #t)
33 (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))
42 (cons 'time (tms:utime (times)))
47 (set! busy-tracing #f))))
49 (define (start-install-tracepoint)
50 (set! trace-thread (current-thread))
53 (define (install-tracepoint)
55 (display "last trace not finished yet\n" (current-error-port))
57 (trap-set! enter-frame-handler record-stack)
58 (trap-enable 'enter-frame)
59 (trap-enable 'traps)))
61 (usleep usecond-interval)
63 (install-tracepoint)))
65 (define-public (mtrace:dump-results base)
66 (define out-graph (open-output-file (format #f "~a.graph" base)))
67 (define stacks-out (open-output-file (format #f "~a.stacks" base)))
71 (format out-graph "# memory trace with ~a points\n" (length trace-points))
76 ((mem (cdr (assoc 'total-cells-allocated r)))
77 (proc (cdr (assoc 'proc r)))
78 (stack (cdr (assoc 'stack r)))
79 (time (cdr (assoc 'time r))))
81 (format out-graph "~a ~a\n" time mem)
84 (format stacks-out "~15a - delta-mem: ~15a - ~a \n" i
85 (- mem last-mem) proc)
88 (stack (cdr (assoc 'stack r)) stack))
89 ((>= j (vector-length stack)))
91 (format stacks-out "\t~a\n"
92 (vector-ref stack j)))))
97 (reverse trace-points)))
101 (define (test-graph . rest)
102 (mtrace:start-trace 100)
105 (mtrace:dump-results "test"))
109 (define (extract-trace continuation)
111 ((stack (make-stack continuation))
112 (depth (min (stack-length stack) mtrace:trace-depth))
113 (trace (make-vector depth #f)))
122 ((source (frame-source (stack-ref stack i))))
125 (cons (source-property source 'filename)
126 (source-property source 'line))))))