Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

top command returns 0% CPU usage when I check my process's CPU usage from within the process

Tags:

c

bash

I have written a C program which needs to get its own CPU and memory usage. So I have written something like this:

        system("prs_pid=`ps | grep prs-m1 | awk '{print $1}'` \n top -n1 | grep -m1 $prs_pid | \
                    awk '{print \"prs_cpu:\" $7 \"\\nprs_mem:\" $6}' >> /stats");

My application name is prs and I do a PS and get the pid of my process and then want to get CPU usage from running TOP. The program reports it is using 2% memory and 0% CPU. But, running the same command manually on the cmd returns the same memry usage but a valid non-zero CPU that I can verify by running top. What I don't understand is why is the cpu usage always 0% when tried from inside the system?

like image 277
bhargava_sg Avatar asked Nov 02 '16 20:11

bhargava_sg


People also ask

Why is my CPU usage 0 percent?

It means that all the processes are stuck waiting... they are "blocked" on thing like user input, network card, hard-drive data, or even ram. Basically it means that the threads are all waiting for the operating system to let them run again.

What is the command to check CPU usage in Photoshop?

The ps command, run periodically, displays the CPU time under the TIME column and the ratio of CPU time to real time under the %CPU column. Look for the processes that dominate usage. The au and v options give similar information on user processes. The options aux and vg display both user and system processes.


1 Answers

When you're running your system command, the current process is suspended (not sure if it is the proper term, but not running at any rate), waiting for the command you ran to end.

While it's suspended, its CPU usage is 0%, which is expected.

To get the correct information, you have to run your system command in a separate thread or process, so your program can keep running.

like image 65
Jean-François Fabre Avatar answered Nov 10 '22 10:11

Jean-François Fabre