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 `.`
This can also be done using shell parameter expansion or via `printf`. For example, running the following two sequences one after the other printed out `1349883230.715` and `1349883230.721` in one run, and `1349884003.025` and `1349884003.032` in another. (The `%N` date format fills with leading zeroes.)

```
  s=$(date +%s.%N); s=${s%??????}; echo $s
  t=$(printf "%20.3f" $(date +%s.%N)); echo $t

```

As mentioned in man bash under *Pattern Matching*, special pattern character `?` matches any single character. As mentioned under *Parameter Expansion*, the form 
`${parameter%word}`
removes a matching suffix pattern: “If the pattern matches a trailing portion ... the expansion is the expanded value of parameter with the shortest matching pattern (the "%" case) or the longest matching pattern (the "%%" case) deleted.”