]> gitweb.factorcode.org Git - factor.git/blob - extra/wordtimer/wordtimer.factor
Append input history to ~/.factor-history upon UI Listener ending
[factor.git] / extra / wordtimer / wordtimer.factor
1 USING: accessors arrays assocs fry io kernel make math
2 math.statistics namespaces prettyprint sequences sorting
3 tools.annotations tools.time vocabs ;
4 IN: wordtimer
5
6 SYMBOL: *wordtimes*
7 SYMBOL: *calling*
8
9 : reset-word-timer ( -- )
10     H{ } clone *wordtimes* set-global
11     H{ } clone *calling* set-global ;
12
13 : lookup-word-time ( wordname -- utime n )
14     *wordtimes* get-global [ drop { 0 0 } ] cache first2 ;
15
16 : update-times ( utime current-utime current-numinvokes -- utime' invokes' )
17     rot [ + ] curry [ 1 + ] bi* ;
18
19 : register-time ( utime word -- )
20     name>>
21     [ lookup-word-time update-times 2array ] keep *wordtimes* get-global set-at ;
22
23 : calling ( word -- )
24     dup *calling* get-global set-at ; inline
25
26 : finished ( word -- )
27     *calling* get-global delete-at ; inline
28
29 : called-recursively? ( word -- t/f )
30     *calling* get-global at ; inline
31
32 : timed-call ( quot word -- )
33     [ calling ] [ [ benchmark ] dip register-time ] [ finished ] tri ; inline
34
35 : time-unless-recursing ( quot word -- )
36     dup called-recursively? not
37     [ timed-call ] [ drop call ] if ; inline
38
39 : (add-timer) ( word quot -- quot' )
40     [ swap time-unless-recursing ] 2curry ;
41
42 : add-timer ( word -- )
43     dup '[ [ _ ] dip (add-timer) ] annotate ;
44
45 : add-timers ( vocab -- )
46     vocab-words [ add-timer ] each ;
47
48 : reset-vocab ( vocab -- )
49     vocab-words [ reset ] each ;
50
51 : dummy-word ( -- ) ;
52
53 : time-dummy-word ( -- n )
54     [ 100000 [ [ dummy-word ] benchmark , ] times ] { } make median ;
55
56 : subtract-overhead ( {oldtime,n} overhead -- {newtime,n} )
57     [ first2 ] dip
58     swap [ * - ] keep 2array ;
59
60 : (correct-for-timing-overhead) ( timingshash -- timingshash )
61     time-dummy-word [ subtract-overhead ] curry assoc-map ;
62
63 : correct-for-timing-overhead ( -- )
64     *wordtimes* [ (correct-for-timing-overhead) ] change-global ;
65
66 : print-word-timings ( -- )
67     *wordtimes* get-global [ swap suffix ] { } assoc>map natural-sort reverse pprint ;
68
69 : wordtimer-call ( quot -- )
70     reset-word-timer
71     benchmark [
72         correct-for-timing-overhead
73         "total time:" write
74     ] dip pprint nl
75     print-word-timings nl ; inline
76
77 : profile-vocab ( vocab quot -- )
78     "annotating vocab..." print flush
79     over [ reset-vocab ] [ add-timers ] bi
80     reset-word-timer
81     "executing quotation..." print flush
82     benchmark [
83         "resetting annotations..." print flush
84         reset-vocab
85         correct-for-timing-overhead
86         "total time:" write
87     ] dip pprint
88     print-word-timings ; inline