Do we have any way to programmatically calculate CPU usage details in app periodically or in any specific method which can probably have high usage For eg - According to Xcode my app uses 128% and 253% respectively. Can we get this figure programmatically and also other possible CPU usage details ?
Do we have any way to programmatically calculate CPU usage details in app periodically or in any specific method which can probably have high usage For eg - According to Xcode my app uses 128% and 253% respectively. Can we get this figure programmatically and also other possible CPU usage details ?
There are actually a few different answer to this questions:
-
This is an area where trying exactly "match" the number(s) we present is going to be an exceedingly tedious process of guesswork and detail fiddling which will never REALLY work. There are multiple APIs for retrieving similar data, each of which will return slightly different numbers (units used, timing differences, etc...). If you manage to use exactly the same API(s) as Xcode, all of these APIs involve polling... so you'll STILL get slightly different data, since there's no way to exactly align with Xcode's polling. Assuming you managed to get that working, the "final" number Xcode presents has been through other processing (it's more like a running average than a realtime indicator), so you'll still look different. Your life will be happier and more fulfilling if you live your own truth instead of trying to match Xcode's.
-
The "best" data (most detailed, "accurate", etc...) comes from the mach APIs, but mach is an API layer I would only use with great reluctance, particularly in any kind of shipping code. Our mach APIs are poorly documented, tricky to use correctly, and, most importantly, they have an incredible ability to create truly ASTONISHING bugs. The two most difficult bugs I've ever investigated were BOTH caused by mach port leaks. In both cases, those leaks came from code that was SPECIFICALLY added to "improve" overall app stability by collecting CPU and memory usage data.
-
The posix function "getrusage" (see man pages for more info) is what I would probably use for this. It's straightforward to use and doesn't require calling into mach.
__
Kevin Elliott
DTS Engineer, CoreOS/Hardware