Measuring execution time of a command in milliseconds
I'm running Ubuntu 18.04 and am new to Ubuntu and Linux in general. I'm trying to measure the execution time of a command down to the millisecond. I would also like to append this time to a file, because I'm doing this a lot of times in a for loop. Finally, I would like to have the most simple and easily readable syntax.
Long story short : I would like the /usr/bin/time
command to return a result precise to the millisecond.
I have read other threads mentioning a time format environment variable, but never how to modify it.
Thanks in advance for the help.
EDIT : Taking all answers into account, the solution was something like
#!/bin/bash
ts=$(date +%s%N)
command
echo "formatting $((($(date +%s%N) - $ts)/1000000)) formatting" >> file_to_append_time_to
The time
command itself is not capable of doing this directly. It does output a time in a fractional format, so it can be parsed back into milliseconds by multiplying by 1000:
$ time sleep 1s
> real 0m1.006s
$ echo '1.006 * 1000' | bc
> 1006.000
This means you can kinda make a command that does it via:
{ time $@ ; } |& grep real | sed -E 's/[^0-9\.]+//g' | tr -d '\n' | (cat && echo " * 1000") | bc
That's essentially parsing the output of time
and multiplying it by 1000. It's a mess because, well, bash.
Probably a better/more useful mess would be this script user Infineight posted on Stack Overflow:
#!/bin/bash
ts=$(date +%s%N)
$@
echo $((($(date +%s%N) - $ts)/1000000))
This (I have expanded it for readability) saves the current nanosecond timestamp from date
, runs the command, then does a subtraction to calculate the time elapsed and formats it into milliseconds.
In my testing they both seemed to yield the same results.