Question: 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](https://github.com/helpermethod/bash-specs/blob/master/src/bash-specs.sh) to see how I implemented this.

Answer: 
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 `.`
Just cut the digits after the first three off from the nanoseconds. 

printf "%d.%.3ss\n" `date +%S` `date +%N` # It might not be terribly unwise to run date only once, btw.

-- print a digit followed by a dot, then treat the next argument as a string and print only the first three characters. 

```

$ i=0; while [ $i -lt 9 ];do i=$((i+1)); sleep 0.1;   \
       printf "%d.%.3ss\n" `date +%S` `date +%N` ;done 
33.917s
34.025s
34.133s
34.240s
34.348s
34.457s
34.566s
34.674s
34.784s

```