Building on a previous question, I need a program that can take a percent between 0% and 100% and then utilize roughly that much of a machine's CPU, in order to test a service that triggers when a certain amount of CPU has been used. I have written some Swift code that can do this for a single core:
// workInterval is the fraction of CPU to use, between 0 (none) and 1 (all).
let workInterval: TimeInterval = <utilization>
let sleepInterval: UInt32 = UInt32((1 - workInterval) * 1_000_000)
let startDate = Date()
var sleepDate = Date()
while startDate.timeIntervalSinceNow > -<time> {
if sleepDate.timeIntervalSinceNow < (workInterval * -1) {
print("Sleep")
usleep(sleepInterval)
sleepDate = Date()
}
}
For 60% utilization, it basically checks our if
condition for 0.6 seconds, and then sleeps for 0.4 seconds, repeating. This works great for whatever individual core the code runs on, but I need to make this work on all cores on a machine. Is there any way to do this in Swift? Am I better off writing this code in another language and executing that script through Swift?
(Yes, this is a very ridiculous task I have been given.)