Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

bash - Print elapsed time in secs with three trailing digits

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use bc command:

elapsed_time_in_ms=$(echo "scale=3;$elapsed_time/1000000" | bc)

The scale basically sets the number of digits you want after the .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...