Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..)

?

like image 209
lewiatan Avatar asked Jun 23 '16 08:06

lewiatan


4 Answers

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
like image 136
anishsane Avatar answered Oct 18 '22 02:10

anishsane


time cat

then press Ctrl-c or Ctrl-d to stop the timer and show the time. The first number is the time.

I've further refined it into this bash alias

alias stopwatch="echo Press Ctrl-c to stop the timer; TIMEFORMAT=%R; time cat; unset TIMEFORMAT"
like image 41
Boris Avatar answered Oct 18 '22 03:10

Boris


If you want something simple that includes minutes, seconds, and centiseconds like a traditional stopwatch you could use sw.

sw

Install

wget -q -O - http://git.io/sinister | sh -s -- -u https://raw.githubusercontent.com/coryfklein/sw/master/sw

Usage

# start a stopwatch from 0, save start time in ~/.sw
sw

# resume the last run stopwatch
sw --resume 
like image 16
Cory Klein Avatar answered Oct 18 '22 01:10

Cory Klein


Here's a nicer function I grabbed a while ago:

function stopwatch() {
    local BEGIN=$(date +%s)
    echo Starting Stopwatch...

    while true; do
        local NOW=$(date +%s)
        local DIFF=$(($NOW - $BEGIN))
        local MINS=$(($DIFF / 60))
        local SECS=$(($DIFF % 60))
        local HOURS=$(($DIFF / 3600))
        local DAYS=$(($DIFF / 86400))

        printf "\r%3d Days, %02d:%02d:%02d" $DAYS $HOURS $MINS $SECS
        sleep 0.5
    done
}
like image 3
Keith Avatar answered Oct 18 '22 03:10

Keith