Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

/usr/bin/time --format output elapsed time in milliseconds

I use the /usr/bin/time program to measure the time for a command. with the --format parameter i can format the output. e.g.

/usr/bin/time -f "%e" ls 

is there a way to output a bigger accuracy of the elapsed seconds? or just output milliseconds, not seconds?

In the manual of /usr/bin/time it only says something about seconds, but maybe there is a way and someone can help me... thanks!

EDIT: I know about the bash command "time" which uses the format of the environment variable "TIMEFORMAT". sorry, but i don't wanna change that env-var... seems to risky to me, solution should be something that doesn't change the running system at all :)

like image 303
Preexo Avatar asked Jun 06 '13 10:06

Preexo


People also ask

How do I print milliseconds in Shell?

date +"%T. %6N" returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds. date +"%T. %3N" returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.

How do I get elapsed time in bash?

Measure Elapsed Time in Milliseconds in Bash To measure elapsed time with millisecond resolution, use date with +%s. %3N option, which returns the current time in milliseconds.

How do I use usr bin time?

Open up a terminal. Run 'type time'. You'll be told that “time is a shell keyword”. Now run 'which time' and you'll see '/usr/bin/time', which looks like a path to a binary.


2 Answers

One possibility is to use the date command:

ts=$(date +%s%N) ; my_command ; tt=$((($(date +%s%N) - $ts)/1000000)) ; echo "Time taken: $tt milliseconds" 

%N should return nanoseconds, and 1 millisecond is 1000000 nanosecond, hence by division would return the time taken to execute my_command in milliseconds.

NOTE that the %N is not supported on all systems, but most of them.

like image 119
devnull Avatar answered Oct 03 '22 14:10

devnull


For convenience I made devnull's answer into a script (I named it millisecond-time).

#!/bin/bash ts=$(date +%s%N) ; $@ ; tt=$((($(date +%s%N) - $ts)/1000000)) ; echo "Time taken: $tt milliseconds" 

I put the script in /usr/local/bin.
Gave it execute rights chmod +x /usr/local/bin/millisecond-time.
Now I can use it like this: millisecond-time my_command

P.s. This would be a comment if I had the rep'.

like image 21
Infineight Avatar answered Oct 03 '22 14:10

Infineight