bash
can show time in microseconds natively!
1. Avoid forks!!!
Having to run date
for each logged line is overkill!!
Prefer to use bash's builtins whenever possible.
At time this question was asked, bash version was bash-4.2.
In this version, the pure bash way for printing current time is:
printf '%(%T)T\n' -1
or
printf '%(%T)T\n' -1
So a short function login each lines with timestamp could be:
logLine() {
printf '%(%T)T %s\n' -1 "$*"
}
Then
$ logLine Hello world.
10:11:32 Hello world.
2. Time in seconds, using printf
builtin:
For storing current time into a variable, you will use:
printf -v varname '%(%T)T' -1
or to store (reusable) UNIX EPOCH:
printf -v varname '%(%s)T' -1
Then
printf 'Stored time stamp is: %(%c)T\n' "$varname"
Stored time stamp is: Sat Jan 27 04:26:00 2018
2.1 Time in seconds, using $EPOCHSECONDS
pseudo variable
From version 5.0-alpha of bash, (2018-05-22) we could use two pseudo variables: $EPOCHSECONDS
and $EPOCHREALTIME
:
man -P'less +/EPOCH' bash
EPOCHREALTIME
Each time this parameter is referenced, it expands to the number
of seconds since the Unix Epoch (see time(3)) as a floating
point value with micro-second granularity. Assignments to
EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses
its special properties, even if it is subsequently reset.
EPOCHSECONDS
Each time this parameter is referenced, it expands to the number
of seconds since the Unix Epoch (see time(3)). Assignments to
EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses
its special properties, even if it is subsequently reset.
echo $EPOCHSECONDS
1692818546
myvar=$EPOCHSECONDS
echo $myvar
1692818547
Sample: Sleep until next minute
sleep $((60-EPOCHSECONDS%60));printf '%(%T)T\n' -1
21:26:00
3. About microseconds
Today, I use bash >= 5.1.4...
From version 5.0-alpha of bash, (2018-05-22):
b. There is an EPOCHSECONDS variable, which expands to the time in seconds
since the Unix epoch.
c. There is an EPOCHREALTIME variable, which expands to the time in seconds
since the Unix epoch with microsecond granularity.
So if you want to use microsecond granularity, function could become:
logLine() {
local now=$EPOCHREALTIME
printf '%(%T)T.%s %s\n' ${now%.*} ${now#*.} "$*"
}
Then
$ logLine Hello world.
10:15:56.862732 Hello world.
Sleep until next minute become a little more complex as bash can't compute real numbers:
slptim=00000$((60000000-${EPOCHREALTIME/.}%60000000));\
printf -v slptim %.6f ${slptim::-6}.${slptim: -6};\
sleep $slptim;\
now=${EPOCHREALTIME};\
printf '%(%H:%M)T:%06.3f\n' ${now%.*} $((${now%.*}%60)).${now#*.}
21:44:00.001
Important: But care! _both variables are not expanded in same way!! See: Don't mix EPOCHREALTIME and EPOCHSECONDS!!!