hedgehog hedgehog - 10 months ago 17
Bash Question

How to use time command but only to time part of the script

just for the record i am running on ksh in a Unix Solaris system.
I have a script that could look like this:

awk '{ do stuff here }'

for n in x {
echo $something | awk '{ do more stuff here }'

I know that i can use
in the console when i am running the script, for example, if the name of the file would be file_name, i would run it like this:
time ksh file_name
, but like this i get returned the run time of the whole script, I need only the run time of the
in order to do some calculations in comparison with another script. Is it even possible that i can invoke the
inside the script, so lets say i would add it before
so that it would calculate only that part? Also i would like to know if it is possible to have two
for one script, so you would get the run time of two different parts of the script.


Since all variables in a Bash script are global, you can store that for in a function and call it prepending time:

my_for_function () {
    for n in x {
        echo $something | awk '{ do more stuff here }'

awk '{ do stuff here }'

time my_for_function   # here you call `time`

Then you run the script normally.

Little example

$ cat silly_script.sh

myfunc() {
    for x in "${a[@]}"
             echo "$x --"
             sleep 1


awk 'BEGIN {print "i am here"}'
a=(1 2 3 4)

time myfunc

echo "i am done"

Let's run it:

$ bash silly_script.sh
i am here
1 --
2 --
3 --
4 --

real    0m4.008s
user    0m0.004s
sys 0m0.000s
i am done