4 ms·
When measuring elapsed times, instead of executing date(1) to get the current time, use $SECONDS: SECONDS Each time this parameter is refe
by cryptonector 8y ago
When measuring elapsed times, instead of executing date(1) to get the current time, use $SECONDS:
SECONDS
Each time this parameter is referenced, the
number of seconds since shell invocation
is returned. If a value is assigned
to SECONDS, the value returned upon
subsequent references is the number of
seconds since the assignment plus the
value assigned. If SECONDS is unset, it
loses its special properties, even if it is
subsequently reset.
Like so:
throttle() {
local -i limit
((limit = SECONDS + $1))
while read line; do
if ((limit < SECONDS)); then
((limit = SECONDS + $1))
echo "$line"
fi
done
}
Try it like so:
$ yes | throttle 2
Of course, that's a bad example in that yes(1) will go as fast as you let it and it always outputs the same thing. In the case of yes(1) the better thing to do would be to sleep between reads, but yes(1) is a special case.
- anothergoogler 8y agoIt's worth noting that OP's example works in any Bourne-compatible shell. I don't think `date +%s` is costly enough to warrant losing the portability.
- kadoban 8y agoI wouldn't be worried about the performance cost of using `date +%s` personally, I'd be concerned about what happens when the user or an automated process changes the system time. For example, what will happen in the debounce function if the user sets the system time backwards by a week after a limit has been set?
- anothergoogler 8y agoGood point, didn't think of that.
- cryptonector 8y agoThe title said bash. Replace "local" with "typeset" and what I wrote is compatible with KSH too -- not Bourne nor POSIX, I know, but still.