]> CyberLeo.Net >> Repos - CDN/shlib.git/blob - lib/sh/stopwatch.sh
Merge branch 'stopwatch'
[CDN/shlib.git] / lib / sh / stopwatch.sh
1 if [ -z "${__stopwatch_sh_loaded}" ]
2 then
3   __stopwatch_sh_loaded=yes
4
5   __stopwatch_sh_VERSION="Stopwatch v0.1"
6   __stopwatch_sh_DESCRIPTION="Stopwatch implementation supporting multiple tagged timers"
7   __stopwatch_sh_COPYRIGHT=$( cat <<"END_OF_COPYRIGHT"
8
9 Copyright (c) 2000-2012, CyberLeo
10 All rights reserved.
11
12 Redistribution and use in source and binary forms, with or without
13 modification, are permitted provided that the following conditions are met:
14
15     * Redistributions of the source code must retain the above copyright
16       notice, this list of conditions, and the following disclaimer.
17     * Redistributions in binary form must reproduce the above copyright
18       notice, this list of conditions, and the following disclaimer in the
19       documentation and/or other materials provided with the distribution.
20     * Neither the name of the organization nor the names of its contributors
21       may be used to endorse or promote products derived from this software
22       without specific prior written permission.
23
24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
28 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
30 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 HOWEVER CAUSED AND ON ANY THEORY OF LIABILTY, WHETHER IN CONTRACT, STRICT
32 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
35 END_OF_COPYRIGHT
36 )
37
38   [ "${kvs}" ] || {
39     kvs="$(mktemp -t ".stopwatch.XXXXXXXX")"
40     trap "rm -f '${kvs}'; exit" exit hup int term kill
41   }
42   want kvs
43
44   stopwatch_help() {
45     cat <<EOF >&2
46 ${__stopwatch_sh_VERSION}
47 ${__stopwatch_sh_DESCRIPTION}
48
49 ${__stopwatch_sh_COPYRIGHT}
50
51 Usage: stopwatch <tag> <start|lap|stop|reset>
52
53 Simple bourne shell based stopwatch
54 Requires 'kvs' and the id 'stopwatch' therein
55 so make sure you set 'kvs' before sourcing this script if necessary.
56
57 After loading, the following commands are available:
58
59 Start a stopwatch
60   stopwatch <tag> start
61
62 'Lap' a stopwatch (emit timer value without stopping)
63   stopwatch <tag> lap
64
65 Stop a stopwatch; can be resumed later with 'start'
66   stopwatch <tag> stop
67
68 Reset a stopwatch back to zero
69   stopwatch <tag> reset
70
71 Internal functions available:
72
73 stopwatch_humany_duration <usec>
74   Transform an integer number of microseconds into a human-readable string
75   (Ex: 3d14h10m3.223s or 7m10.013s )
76
77 stopwatch_set_message_callback <command>
78   Register a callback to format event messages emitted when a stopwatch is
79   commanded. The callback will receive the following parameters:
80     <command> - one of: starting, started, lap, get, stopping, stopped, reset
81     <tag>     - stopwatch name
82     <time>    - the current time on the stopwatch, if any
83     <delta>   - the time since the last change or inquiry (for lap and stopping)
84   The commands are as follows:
85     starting  - called start while stopped
86     started   - called start while running
87     lap       - called lap while running
88     get       - called lap while stopped
89     stopping  - called stop while running
90     stopped   - called stop while stopped
91     reset     - called reset
92
93 EOF
94     kill -ABRT $$
95   }
96
97   case "$(uname -s)" in
98   Linux)
99     _stopwatch_usec() {
100       echo $(( $(date +%s%N) / 1000 ))
101     }
102     ;;
103   FreeBSD)
104     _stopwatch_usec() {
105       "${_root}/lib/sh/usec" || echo $(( $(date +%s) * 1000000 ))
106     }
107     ;;
108   *)
109     echo "Unsupported platform: $(uname -s)" >&2
110     exit 1
111     ;;
112   esac
113
114   # Format stopwatch event messages (Can be overridden; see
115   # 'stopwatch_set_message_callback')
116   _stopwatch_message_callback() {
117     command="${1}"
118     tag="${2}"
119     time="${3:+$(stopwatch_humany_duration ${3})}"
120     delta="${4:+$(stopwatch_humany_duration ${4})}"
121     printf "Stopwatch: "
122     case "${command}" in
123     starting)  printf "'%s' starts%s.\n" "${tag}" "${time:+ at ${time}}";;
124     started)   printf "'%s' is already running.\n" "${tag}" ;;
125     lap)       printf "'%s' is running: %s%s\n" "${tag}" "${time}" "${delta:+ (${delta} since last lap)}" ;;
126     get)       printf "'%s' is stopped: %s\n" "${tag}" "${time}" ;;
127     stopping)  printf "'%s' stops at %s%s.\n" "${tag}" "${time}" "${delta:+ (${delta} since last start)}" ;;
128     stopped)   printf "'%s' is stopped%s.\n" "${tag}" "${time:+ at ${time}}" ;;
129     reset)     printf "'%s' is reset to zero.\n" "${tag}" ;;
130     *)         printf "No message for command %s\n" "${command}" ;;
131     esac
132   }
133
134   # Set the message callback
135   stopwatch_set_message_callback() {
136     _stopwatch_registered_message_callback="${1:-_stopwatch_message_callback}"
137     kvs_set stopwatch message_callback "${_stopwatch_registered_message_callback}"
138   }
139
140   # Fetch the message callback; default if unset
141   stopwatch_get_message_callback() {
142     [ "${_stopwatch_registered_message_callback}" ] ||
143       _stopwatch_registered_message_callback="$(kvs_get stopwatch messsage_callback)"
144     if [ "${_stopwatch_registered_message_callback}" ]
145     then
146       echo "${_stopwatch_registered_message_callback}"
147     else
148       _stopwatch_registered_message_callback=_stopwatch_message_callback
149       echo _stopwatch_message_callback
150     fi
151   }
152
153   # Try and format a passed integer number of seconds into something more
154   # easily parseable by a human (like 6m10s or something)
155   stopwatch_humany_duration() {
156     local usec secs mins hurs days
157     [ "${1}" -a "$(echo "${1}" | tr -Cd '0-9')" = "${1}" ] || return 255
158     usec=$(( ${1} % 1000000 ))
159     secs=$(( ${1} / 1000000 ))
160     mins=0
161     hurs=0
162     [ "${secs}" -lt 60 ] || {
163       mins=$(( ${secs} / 60 ))
164       secs=$(( ${secs} % 60 ))
165     }
166     [ "${mins}" -lt 60 ] || {
167       hurs=$(( ${mins} / 60 ))
168       mins=$(( ${mins} % 60 ))
169     }
170     [ "${mins}" -gt 0 ] || mins=""
171     [ "${hurs}" -lt 24 ] || {
172       days=$(( ${hurs} / 24 ))
173       hurs=$(( ${hurs} % 24 ))
174     }
175     [ "${hurs}" -gt 0 ] || hurs=""
176
177     printf "%s%s%s%s.%03ds" "${days:+${days}d}" "${hurs:+${hurs}h}" "${mins:+${mins}m}" "${secs}" "$(( ${usec} / 1000 ))"
178   }
179
180   # Start a named stopwatch, but do nothing if the named stopwatch is already
181   # running.
182   stopwatch_start() {
183     name="${1:-stopwatch}"
184     [ "${nao}" ] || nao="$(_stopwatch_usec)"
185     # Is the stopwatch running?
186     if kvs_has_key stopwatch "${name}"
187     then
188       eval "$(stopwatch_get_message_callback) started ${name}"
189     else
190       # start the stopwatch
191       accum="$(kvs_get stopwatch "${name}_accumulator")"
192       kvs_set stopwatch "${name}" "${nao}"
193       [ "${accum}" ] && kvs_set stopwatch "${name}_laptime" "${nao}"
194       eval "$(stopwatch_get_message_callback) starting ${name} ${accum}"
195     fi
196   }
197
198   # 'Lap' the named stopwatch: print out a line indicating how long the named
199   # stopwatch has been running, but do not stop nor reset the stopwatch.
200   stopwatch_lap() {
201     name="${1:-stopwatch}"
202     [ "${nao}" ] || nao="$(_stopwatch_usec)"
203     # Is the stopwatch running?
204     if kvs_has_key stopwatch "${name}"
205     then
206       # emit a line indicating how long it has been running
207       start="$(kvs_get stopwatch "${name}")"
208       accum="$(kvs_get stopwatch "${name}_accumulator")"
209       laptm="$(kvs_get stopwatch "${name}_laptime")"
210       delta="$(( ${nao} - ${start} ))"
211       [ "${laptm}" ] && laptm="$(( ${nao} - ${laptm} ))"
212       [ "${accum}" ] && delta="$(( ${delta} + ${accum} ))"
213       kvs_set stopwatch "${name}_laptime" "${nao}"
214       eval "$(stopwatch_get_message_callback) lap ${name} ${delta} ${laptm}"
215     else
216       accum="$(kvs_get stopwatch "${name}_accumulator")"
217       eval "$(stopwatch_get_message_callback) get ${name} ${accum}"
218     fi
219   }
220
221   # Stop the named stopwatch and print out a line indicating how long it had
222   # been running up until that point; do not reset the stopwatch.
223   stopwatch_stop() {
224     name="${1:-stopwatch}"
225     [ "${nao}" ] || nao="$(_stopwatch_usec)"
226     if kvs_has_key stopwatch "${name}"
227     then
228       start="$(kvs_get stopwatch "${name}")"
229       accum="$(kvs_get stopwatch "${name}_accumulator")"
230       delta="$(( ${nao} - ${start} ))"
231       diffs="${delta}"
232       [ "${accum}" ] && delta="$(( ${delta} + ${accum} ))"
233       kvs_set stopwatch "${name}_accumulator" "${delta}"
234       kvs_unset stopwatch "${name}"
235       kvs_unset stopwatch "${name}_laptime"
236       eval "$(stopwatch_get_message_callback) stopping ${name} ${delta} ${diffs}"
237     else
238       accum="$(kvs_get stopwatch "${name}_accumulator")"
239       eval "$(stopwatch_get_message_callback) stopped ${name} ${accum}"
240     fi
241   }
242
243   # Reset the named stopwatch back to zero.
244   stopwatch_reset() {
245     name="${1:-stopwatch}"
246     [ "${nao}" ] || nao="$(_stopwatch_usec)"
247     kvs_unset stopwatch "${name}"
248     kvs_unset stopwatch "${name}_accumulator"
249     kvs_unset stopwatch "${name}_laptime"
250     eval "$(stopwatch_get_message_callback) reset ${name}"
251   }
252
253   stopwatch() {
254     [ "${1}" -a "${2}" ] || stopwatch_help;
255     nao="$(_stopwatch_usec)"
256     case "${2}" in
257     [Ss][Tt][Aa][Rr][Tt])  stopwatch_start "${1}"  ;;
258     [Ll][Aa][Pp])          stopwatch_lap "${1}"    ;;
259     [Ss][Tt][Oo][Pp])      stopwatch_stop "${1}"   ;;
260     [Rr][Ee][Ss][Ee][Tt])  stopwatch_reset "${1}"  ;;
261     *)                     stopwatch_help          ;;
262     esac
263   }
264 fi