Search code examples
linuxbashtimemillisecondsseconds

time part of a script (running time)


With the time script.sh you will get the time it took to run a script, BUT if you want to time a part of the script?

let's say I want to test how long a loop takes, I could use the $SECONDS function, but is there any timer that counts milliseconds?

for example in the middle of a long code:

    timerstart
    until [[ $loop -eq 10000 ]]; do
     ((++loop))

    echo "annoying"
    done
    timerstop

and then in the end of the script, I just add echo $timerresult , and it will display how many milliseconds it took to run only the selected code, and not the rest of the script

I'm looking for this solution so I can test parts of scripts for "slowness".. is this possible to solve?


Solution

  • For Bash 5.0 and later, you can use $EPOCHREALTIME:

    [...] it expands to the number of seconds since the Unix Epoch as a floating point value with micro-second granularity [...]

    start=$EPOCHREALTIME
    for ((i = 0; i < 10000; ++i)); do
        echo "annoying"
    done
    stop=$EPOCHREALTIME
    
    elapsed=$(bc -l <<< "$stop - $start")