Calculating the CPU usage of any process in Linux
The proc sytem gives all the information you need to calculate CPU usage at any interval you want.
I wanted to easily calculate CPU usage of specific processes at given intervals. Turns out this is very easy to do.
Simply collect the stat information:
Add the 14th and 15th columns together and that’s the total clock ticks used by that process.
Now wait a specified duration (say 2 seconds) and collect that information again. Take the difference between total clock ticks between the two times, and then divide by the duration that elapsed. This is the total clock ticks used by that process during that time.
To convert the total clock ticks to time, you’ll need to divide clock ticks per second which you can get with a simple command:
Here’s a simple Go implementation I made: example in Go and another example I found online for one written in bash: example in bash.