Ever want to get timestamps in Bash? Probably not, there's date
to solve that need. How about high resolution timestamps in Bash so you can profile your functions? Ok, I admit this a bit of a niche. However, the unit test framework and the bench tester both needed this functionality, so I offer it as a library.
A key point is that the time::stampDiff
function does not use any external programs. It computes a decimal time difference with just built-in integer math.
Add to your bpm.ini
file the following dependency.
[dependencies]
time=*
Run bpm install
to add the library. Finally, use it in your scripts.
#!/usr/bin/env bash
. bpm
bpm::include time
time::stamp startTime
Get a timestamp (seconds only).
- $1 - Destination variable name.
Examples
time::stamp seconds
echo "$seconds" # 1499716539
Returns nothing.
Determine the difference between two timestamps. Works with low resolution and high resolution time stamps.
- $1 - Destination variable name.
- $2 - Starting time (the smaller number).
- $3 - Ending time.
The time is limited to an accuracy of 9 digits beyond the decimal point because Bash can be compiled to use 32-bit math, whose limit is a signed 2147483648, easily holding 9 digits. It also works when we have to hold the extra digit from carrying a 1 from the whole numbers.
Examples
time::stampDiff result 1499716539 1499716649.266348007
echo "$result" # 110.266348007
Returns nothing.
Calculate the seconds of difference.
Get a high-resolution timestamp, at least at millisecond resolution.
$1 - Destination variable name.
Examples
# Bash 3.x and 4.x
time::stampHr timestamp
echo "$timestamp" # 1499716649.266348007
# Bash 5.x (much, much faster)
time::stampHr timestamp
echo "$timestamp" # 1551362098.463254
Returns nothing.