in bash date elapsedTime coreutils gnu value too great for base ~ read.

Measuring elapsed time in milliseconds in bash

I was working on a Telemetry project in my company and I had to instrument some of our bash scripts with code that would measure elapsed time of script execution. You can easily achive this with the following code

calculate_duration() {
    # Start time in nanoseconds
    start_time=$(date +%s%N)

    "$@"

    # End time in nanoseconds
    end_time=$(date +%s%N)

    # Calculate duration in nanoseconds
    duration_ns=$((end_time - start_time))

    # Convert duration to milliseconds
    duration_ms=$((duration_ns / 1000000))

    echo "$duration_ms"
}

# Test
time_in_ms=$(calculate_duration sleep 0.5)
echo "Execution time: $time_in_ms ms"

One thing to keep in mind for this. With different bash versions you can end up with a different behaviour of date utility.
With bash V3 the $(date +%s%N) command will return something like 1692824647N: and when you will try to calculate the different you will end up with 1692824647N: value too great for base error. In bash V4 this problem is solved, but if you still on bash 3 and you want to overcome this problem then it's better to use /usr/local/gnu/coreutils/bin/date library from GNU coreutils. On a mac you can easily install it with brew :

brew install coreutils
comments powered by Disqus
comments powered by Disqus