Search code examples
bashmathtimetimerbash-function

How can I create a stopwatch in bash?


I created a simple stopwatch (bash function) for counting time, but for now it's showing current time with milliseconds.

The code:

function stopwatch() {
    date +%H:%M:%S:%N
    while true; do echo -ne "`date +%H:%M:%S:%N`\r"; done;
}

I tried to change it as explained in this answer, but it works only with second since Unix Epoch.

When I used date format +%s.%N the subtraction from the answer above stopped working due to the fact that bash subtraction takes only integer.

How can I solve it and have a terminal stopwatch that prints time like so:

0.000000000
0.123123123
0.435345345
(and so on..)

?


Solution

  • One possible (& hacky) mechanism that can work for a day:

    $ now=$(date +%s)sec
    $ while true; do
         printf "%s\r" $(TZ=UTC date --date now-$now +%H:%M:%S.%N)
         sleep 0.1
      done
    

    Bonus: You can press enter at any time to get the LAP times. ;-)

    Note: This is a quick fix. Better solutions should be available...

    watch based variant (same logic):

    $ now=$(date +%s)sec; watch -n0.1 -p TZ=UTC date --date now-$now +%H:%M:%S.%N