So the built-in time function for bash should output in this format
real 0m0.002s
user 0m0.001s
sys 0m0.000s
I want to save the user time in milliseconds, like 001 what's a clean way to do this?
So the built-in time function for bash should output in this format
real 0m0.002s
user 0m0.001s
sys 0m0.000s
I want to save the user time in milliseconds, like 001 what's a clean way to do this?
Using bash's built in string globbing you could do something like this:
Results running
bash -x
Bash's
time
builtin is a bit tricky to capture because it has special handling so that it can return the processing time for an entire pipeline liketime ls -l | sort | uniq
rather than just the processing time for only thels -l
command in my example.The best way to capture just the output of time is the following redirection technique:
At this point if you were to
echo "$foo"
you would see something on the order ofNow to get just the
004
part of that you have quite a few options: sed, awk or straight bash to name the top 3. My personal favorite would be awk and it would look something like this:Now if you were to
echo "$foo"
you would see just004
as desiredThe clean way is to use the
TIMEFORMAT
shell variable to only print the user information. (man bash
for more details.)Then, of course you need to capture the output from it. This is impossible to do from the pipeline, as it's done internally by the shell, but you can run it in a subshell, and the output will go to standard error. But then you have to somehow redirect the output of the command elsewhere. Here, I just discard it, but many other possibilities exist, depending on exactly what you need to do. Then you need to munge
d.ffffd
intoffffdd
. Just deleting the period will do so.If you like, you can add
| sed s/^0*//
to eliminate the leading zeroes.%R will give real time, %S system time. You can change the precision with e.g. %6U to get microseconds, though most systems won't be anywhere near that accurate.
man bash
for help on redirections.man tr
andman sed
for help on how to use them.