[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [minor] "precision" of $SECONDS
From: |
Linda Walsh |
Subject: |
Re: [minor] "precision" of $SECONDS |
Date: |
Thu, 25 Feb 2016 03:03:41 -0800 |
User-agent: |
Thunderbird |
Stephane Chazelas wrote:
$ time bash -c 'while ((SECONDS < 1)); do :; done'
bash -c 'while ((SECONDS < 1)); do :; done' 0.39s user 0.00s system 99% cpu
0.387 total
That can take in between 0 and 1 seconds. Or in other words,
$SECONDS becomes 1 in between 0 and 1 second after the shell was
started.
The format you are using to display output of 'time' doesn't show
real time -- only CPU seconds.
Try:
TIMEFORMAT='%2Rsec %2Uusr %2Ssys (%P%% cpu)'
It shows the real, "clock" time, as well as
the standard % formula of cpu-secs/real-secs -- which can give
up to #Cores x 100"%" as value for %cpu stretches the standard
def of "percent", but is at least more honest than grouping
all cpu's together as "1 cpu", and showing 100% usage of 1 core
on a 12-core machine as "8.3%".
mksh and zsh behave like bash (I'll raise the issue there as
well).
With zsh (like in ksh93), one can do "typeset -F SECONDS" to
make $SECONDS floating point, which can be used as a work around
of the "issue".
----
With linux, one can read /proc/uptime to 100th's of a sec, or
use date to get more digits. A middle of the road I used for
trace timing was something like:
function __age { declare ns=$(date +"%N"); declare -i
ms=${ns##+(0)}/1000000;
printf "%4d.%03d\n" $SECONDS $ms
}
Then I add that in my PS4 prompt:
## for *relative* script exec speed, only!
## (slows down normal speed significantly):
#export
PS4='>[$(__age)]${BASH_SOURCE:+${BASH_SOURCE[0]/$HOME/\~}}#${LINENO}${FUNCNAME:+(${FUNCNAME[0]})}>
'
On cygwin, calling 'date' was a deal breaker, so I just used /proc/uptime
to get the relative time down to centiseconds.
As you can see, I wanted the times
relative to the start of a given script, thus used SECONDS for that.
Given the overhead of calling 'date', the times printed are easily
20-50x slower
than w/o the time -- BUT, as the comment says above, it's good for
determining relative differences -- not only times for each command, but
also algorithmic differences, as the overhead is relatively constant.