Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to get only memory peak usage with /usr/bin/time?

I am building a script with usr/bin/time program to monitor the RAM usage of a script and storing it in a variable so i can check if it is higher than a specified limit $mlimit, like this example using ls / as the command:
I am building a script with usr/bin/time program to monitor the RAM usage of a script and storing it in a variable so i can check if it is higher than a specified limit $mlimit, like this example using ls / as the command:


/usr/bin/time in this case returns first the output of the command and then the maximum resident set size (RAM usage). I thought then i could reverse the output, cut it to get the ram usage and reverse it back. But i get this output: RAM usage: bin. bin is the first directory returned by the ls / command. So my strategy to get the RAM usage is not working.

Thanks
by

1 Answer

Kajalsi45d
GNU time outputs the resource usage information on stderr, though can be told to write it elsewhere with -o
{
musage=$(command time -o /dev/fd/4 -f %M ls / 4>&1 >&3 3>&-)
} 3>&1


Would record the max memory usage in the variable whilst leaving ls' stdout and stderr alone.

That works by duplicating the original fd 1 (stdout) to fd 3 outside the command substitution with 3>&1, so that inside the command substitution, we can restore the original stdout for ls with >&3 after having made the command substitution pipe available on fd 4.

Then time writes its output to that pipe via /dev/fd/4, while ls stdout is the original one.

Login / Signup to Answer the Question.