How to get overall CPU usage in iOS Swift 4.x

i0S Swift Issue

The code below will help you get the CPU usage values. It is useful to build a log system for your iOS application with Swift.

What is a CPU tick?

tick is an arbitrary unit for measuring internal system time. There is usually an OS-internal counter for ticks; the current time and date used by various functions of the OS are derived from that counter.

How many milliseconds a tick represents depends on the OS, and may even vary between installations. Use the OS’s mechanisms to convert ticks into seconds.

As to why a thread reports it’s not being called: That will depend on whether the thread is blocking somewhere (waiting, I/O etc.). If it is not blocking, then yes, the OS’s scheduler will decide when it gets to run, which may be a long time if the system is busy.

Get overall CPU usage not of a single app

The CPU statistics is obtained by calling host_statistics() and the “flavor” argument must be HOST_CPU_LOAD_INFO. hostInfo contains the pointer to the allocated structure, so that value must be rebound, not the address of the variable.

Alternatively, use a local variable instead of allocating and releasing the host_cpu_load_info structure:

Result Log: