For a framework I'm writing I would like to measure how much a piece of (bash) code takes to execute and then print the elapsed time in seconds.
For measuring, I do the following:
start=$(date +%s%N)
# do something here
elapsed_time=$(($(date +%s%N) - start))
This gives me the elapsed seconds concatenated with the elapsed nanos. If I now divide this by 1000000, I'll get the time in ms
elapsed_time_in_ms=$(($elapsed time / 1000000))
This is all nice and seems to work but the real problem is that I want to print it in this format:
12.789s
where before the .
are the seconds and after the dot are last 3 digits of the ms value.
How would I achieve something like that?
EDIT
I am aware that the time would probably not of much use, still I would like to implement this (even if only for cosmetic reasons :-)).
EDIT 2
For anyone facing the same problem:
In the end I've chosen to use time as it doesn't require a fork and seems to be the most portable solution.
Have a look at the it
function and the global total_elapsed_time
variable here to see how I implemented this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…