Get the load, cpu usage and time of executing a bash script

5.3k views Asked by At

I have a bash script that I plan to run every 5 or 15 mins using crontab based on the load it puts on server.

I can find time of running the script, but load, memory usage and CPU usage I am not sure how to find.

Can someone help me?

Also any suggestions of rough benchmark that will help me decide if the script puts too much load and should be run every 15 mins and not 5 mins.

Thanks in Advance!

3

There are 3 answers

2
Yogesh On BEST ANSWER

You can use "top -b", top gives the CPU usage, memory usage etc, Insert these lines in your script, this will process in background and will terminate the process as soon as your testing overs.

 ssh server_name "nohup top -b -d 0.5 >> file_name &"   

\top process will run in background because of &, -d 0.5 will give you the cpu status at every 0.5 secs, redirect the output in file_name for latter analysis.

for killing the process after your test, insert following in your script,

ssh server_name "kill \`ps -elf | grep 'top -b' | grep -v grep | sed 's/  */ /g' |cut -d ' ' -f4\`"

Your main testing script should be between top command and command for killing top.

I presumed you are running the script from client side, if not ignore "ssh server_name".

If you are running it from client side, because of "ssh", you will be asked for the password, for avoiding this follow these 3 simple steps

This will definitely solve the issue.

0
deimus On

You can check following utilities

Although you might need to make measurements also for the child processes of your executable, in order to collect summarizing information

0
whereswalden On

For memory, use free -m. Your actual memory available is the second number next to +/- buffers/cache (in megabytes with -m) (source).

For CPU, it's a bit more complicated. Start by looking at cat /proc/stat | grep 'cpu ' (note the space). You'll see something like this:

cpu  2255 34 2290 22625563 6290 127 456

The columns are from left to right, "user, nice, system, idle". CPU usage is usually calculated as (user+nice+system) / (user+nice+system+idle). However, these numbers show the number of "time units" that the CPU has spent doing that thing since boot, and thus are always increasing. If you were to do the aforementioned calculation, you'd get the CPU usage average since boot. To get a point-in-time usage, you have to take 2 samples, find their difference, and calculate the usage from that. To be clear, that will be the average CPU usage between your samples. (source)