Reputation: 928
Is there any way that I can, over a period of say a day, see how much CPU (or battery) each app uses? Here's a sample from BatteryDoctor app:
I think they did some works programmatically like:
From that, they can "calculate" the battery usage per app (in percent).
I know there is some way to get the second work (Data Usage). But for the first one, seems like it's really hard to get.
I've found some ways, but they seems don't work
"/proc/" + pid + "/stat"
way)- I can't run this one, seems like toks[2] is always "S""sh -c top -m 1000 -d 1 -n 1 | grep \"" + pid + "\" "
). In anyway, it only can return the percent of CPU which app is using. But I want the time of CPU which app's used for a period (like 24 hours in the example).
So does anyone know how to get that CPU time per app programmatically ? Or maybe it just the foreground/running time of an app?
Upvotes: 3
Views: 3095
Reputation: 1511
Here's the answer to your question, but I'm unsure if it's really what you want.
If top calculates the %CPU of an app, let's call it %CPU_APP, over a window of, say 500ms, then the total time the app spends executing is 500ms*%CPU_APP over that interval. If you sum up all such intervals over, say 24 hrs, then you get the total amount of time the app used the processor in that period.
For example, say the window is 500ms and the %CPU_APP is 20%, then the app uses 100ms of that time. If the %CPU_APP is constant over 24 hrs, then the total time the app spends running is 24hrs*60min/hr*60sec/min*.5*%CPU_APP. (I leave the math to the reader ;-)> )
The difficult part is finding the size of the window. You might be able to measure this by eyeballing the graininess of the plot if it isn't given in any documentation. And the %CPU_APP is unlikely to be constant so you'll have to collect those statistics and integrate over time.
If this isn't the answer you want, please clarify your question and resubmit to stack overflow.
Upvotes: 4