Reputation: 6945
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.)
Upvotes: 1
Views: 1514
Reputation: 318854
Most likely you can achieve what you want with a concurrent queue. Add one instance of your above code to the queue for each available core. Then each of those instances should run in parallel - one on each core.
Though you might need to run one on the main queue and then run "cores - 1" instances on the concurrent queue.
But in the end you don't have any control over how the cores are utilized. The above relies on the runtime making good use of the available cores for you.
Upvotes: 2