Home > Blockchain >  iOS Swift - How can I cause intentional CPU usage?
iOS Swift - How can I cause intentional CPU usage?

Time:04-04

I have a question that other people usually have a problem with.

I am building an application that measures battery discharge.

My plan is to simulating high CPU usage and then measure the time it took the battery to drop to a certain level

Question: How can I cause high CPU usage on purpose without blocking the UI?

It would be very nice if someone could give me a tip.. I didn't find anything.

EDIT: Can i do something like that ?

DispatchQueue.global(qos: .background).async { [weak self] in
        guard let self = self else { return }
        for _ in 0..<Int.max {
            while self.isRunning {
            }
            break
        }
    }

CodePudding user response:

What you want is persistent load on CPU, with number of threads concurrently loading CPU >= number of CPUs.

So something like

DispatchQueue.concurrentPerform(iterations: 100) { iteration in
    for _ in 1...10000000 {
        let a = 1   1
    }
} 

Where:

  • The concurrentPerform with iterations set to 100 makes sure we are running in parallel using every available thread. This is overkill of course, would be enough 4 threads to get every CPU busy on quad core, and about 10 threads is what iOS typically allocates at max per process. But 100 simply makes ruee it really happens)
  • The 1...10000000 makes loop really really long
  • The let a = 1 1 gives CPU something to do.

On my iPhone 8 simulator running this code created a picture like this (stopped it after about 30 sec): enter image description here

Careful though! You may overheat your device

  • Related