2

I'm calling the Linux top -n 1 -b command from a Qt application to get the free CPU percentage. This application calls this command every 3 seconds, but the CPU usage seems to be updated only the first time the command is invoked in the application and then save this value in cache (only the CPU usage, all others values are updated with every call). If I manually test the "top -n 2 -b" command on console the "realtime" CPU is updated only after the second iteration. I can't wait for the second iteration in my application to update the CPU value so I was wondering if there is some system variable or cache that can be modified to get this value update on the first iteration.

1
  • I'd suggest you to parse /proc/stat instead of calling top from your application.
    – UVV
    Oct 26, 2015 at 10:52

1 Answer 1

1

Each top iteration reads /proc/stat cpu lines and compares values to those from previous read, which are zeroes on first iteration. Comparing to values you've got 3 seconds ago gives you average CPU states distribution for those 3 seconds. Comparing to zeroes gives you average for whole system uptime (/proc/stat has all zeros on system boot), i.e. you have valid percentages on first top iteration, but averaged for much longer period of time, therefore seemed not to update.

When parsing /proc/stat manually, one still needs two reads in different moments of time.

1
  • But how to get CPU information about each process in the system as it top does?
    – JavaRunner
    Jun 9, 2020 at 1:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .