1 USING: kernel sequences namespaces math assocs words arrays tools.annotations vocabs sorting prettyprint io micros math.statistics accessors ;
7 : reset-word-timer ( -- )
8 H{ } clone *wordtimes* set-global
9 H{ } clone *calling* set-global ;
11 : lookup-word-time ( wordname -- utime n )
12 *wordtimes* get-global [ drop { 0 0 } ] cache first2 ;
14 : update-times ( utime current-utime current-numinvokes -- utime' invokes' )
15 rot [ + ] curry [ 1+ ] bi* ;
17 : register-time ( utime word -- )
19 [ lookup-word-time update-times 2array ] keep *wordtimes* get-global set-at ;
22 dup *calling* get-global set-at ; inline
24 : finished ( word -- )
25 *calling* get-global delete-at ; inline
27 : called-recursively? ( word -- t/f )
28 *calling* get-global at ; inline
30 : timed-call ( quot word -- )
31 [ calling ] [ >r micro-time r> register-time ] [ finished ] tri ; inline
33 : time-unless-recursing ( quot word -- )
34 dup called-recursively? not
35 [ timed-call ] [ drop call ] if ; inline
37 : (add-timer) ( word quot -- quot' )
38 [ swap time-unless-recursing ] 2curry ;
40 : add-timer ( word -- )
41 dup [ (add-timer) ] annotate ;
43 : add-timers ( vocab -- )
44 words [ add-timer ] each ;
46 : reset-vocab ( vocab -- )
47 words [ reset ] each ;
51 : time-dummy-word ( -- n )
52 [ 100000 [ [ dummy-word ] micro-time , ] times ] { } make median ;
54 : subtract-overhead ( {oldtime,n} overhead -- {newtime,n} )
56 swap [ * - ] keep 2array ;
58 : change-global ( variable quot -- )
59 global swap change-at ;
61 : (correct-for-timing-overhead) ( timingshash -- timingshash )
62 time-dummy-word [ subtract-overhead ] curry assoc-map ;
64 : correct-for-timing-overhead ( -- )
65 *wordtimes* [ (correct-for-timing-overhead) ] change-global ;
67 : print-word-timings ( -- )
68 *wordtimes* get-global [ swap suffix ] { } assoc>map natural-sort reverse pprint ;
70 : wordtimer-call ( quot -- )
72 [ call ] micro-time >r
73 correct-for-timing-overhead
74 "total time:" write r> pprint nl
75 print-word-timings nl ;
77 : profile-vocab ( vocab quot -- )
78 "annotating vocab..." print flush
79 over [ reset-vocab ] [ add-timers ] bi
81 "executing quotation..." print flush
82 [ call ] micro-time >r
83 "resetting annotations..." print flush
85 correct-for-timing-overhead
86 "total time:" write r> pprint