1 USING: accessors arrays assocs fry io kernel make math
2 math.statistics namespaces prettyprint sequences sorting
3 tools.annotations tools.time vocabs ;
4 FROM: namespaces => change-global ;
10 : reset-word-timer ( -- )
11 H{ } clone *wordtimes* set-global
12 H{ } clone *calling* set-global ;
14 : lookup-word-time ( wordname -- utime n )
15 *wordtimes* get-global [ drop { 0 0 } ] cache first2 ;
17 : update-times ( utime current-utime current-numinvokes -- utime' invokes' )
18 rot [ + ] curry [ 1 + ] bi* ;
20 : register-time ( utime word -- )
22 [ lookup-word-time update-times 2array ] keep *wordtimes* get-global set-at ;
25 dup *calling* get-global set-at ; inline
27 : finished ( word -- )
28 *calling* get-global delete-at ; inline
30 : called-recursively? ( word -- t/f )
31 *calling* get-global at ; inline
33 : timed-call ( quot word -- )
34 [ calling ] [ [ benchmark ] dip register-time ] [ finished ] tri ; inline
36 : time-unless-recursing ( quot word -- )
37 dup called-recursively? not
38 [ timed-call ] [ drop call ] if ; inline
40 : (add-timer) ( word quot -- quot' )
41 [ swap time-unless-recursing ] 2curry ;
43 : add-timer ( word -- )
44 dup '[ [ _ ] dip (add-timer) ] annotate ;
46 : add-timers ( vocab -- )
47 vocab-words [ add-timer ] each ;
49 : reset-vocab ( vocab -- )
50 vocab-words [ reset ] each ;
54 : time-dummy-word ( -- n )
55 [ 100000 [ [ dummy-word ] benchmark , ] times ] { } make median ;
57 : subtract-overhead ( {oldtime,n} overhead -- {newtime,n} )
59 swap [ * - ] keep 2array ;
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 -- )
73 correct-for-timing-overhead
76 print-word-timings nl ; inline
78 : profile-vocab ( vocab quot -- )
79 "annotating vocab..." print flush
80 over [ reset-vocab ] [ add-timers ] bi
82 "executing quotation..." print flush
84 "resetting annotations..." print flush
86 correct-for-timing-overhead
89 print-word-timings ; inline