1

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.)

Community
  • 1
  • 1
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
  • Just use `Dispatch` for multithreading. But besides that, you'll probably have a much easier time properly simulating a specific CPU usage by making an application that uses 100%, then limiting its CPU access at the OS level. – Alexander Jan 24 '17 at 23:02
  • @Alexander unfortunately I do not believe that is within our control in this scenario. – TheSoundDefense Jan 24 '17 at 23:03
  • @TheSoundDefence you can't use `nice` or `cpulimit`? – Alexander Jan 24 '17 at 23:04
  • @Alexander I don't think we can guarantee anything of the sort, no. We are not assuming this application will run on a server we control. – TheSoundDefense Jan 24 '17 at 23:06
  • 1
    @TheSoundDefence As the first immutable law of security goes: "If a bad guy can persuade you to run his program on your computer, it’s not solely your computer anymore." You are the captain now :p You can use `Process` to launch arbitrary binaries. You can call `cpulimit` from there :) – Alexander Jan 24 '17 at 23:11

1 Answers1

2

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579