Create a progress bar for a selected process' CPU value #25
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What does this do?
Part of #6
This creates a progress bar for the selected process' CPU usage. The progress bar is out of 100%.
How is this accomplished?
This makes use of the
popen
command. We use this to open a process command and read the values that it returns.How to parse the output of a Linux command.
The following code snippet is from Chromium, an open source web browser provided by Google:
Sketch of the math:
Basically, we calculated the CPU percentage based on how long the process has been running. This is how long it has been running on the CPU, not as if the program was just opened now. We found this value by using the top command. To use an example:
Imagine that a process has been running for 30 seconds. If we check it again 1 second later and the process has been running on the CPU for 30.2 seconds, then we subtract the previous time from the current time:
30.2 - 30 = 0.2 seconds running on the CPU in 1 second.
0.2 * 100 = 20%.
This means that the process is taking up 20% of the CPU. In our case, we're checking on intervals of 5 seconds, so we subtract the final number by 5.
What did I learn?
ps
doesn't actually return the current CPU percentage for a running process. Whiletop
is monitoring,ps
gives you the average percentage over the life of the program. More context here.