title: Swift: Limit CPU time of thread, queue or operation
body: <p>I employ a native C library in my iOS app. Calling the code directly puts it on the main thread (of course depending on from where I call it) so I have created a new queue in order to leave the main thread for the call.</p>
  <pre><code>let cProcessingQueue = DispatchQueue(label: &quot;cProcessingQueue&quot;)
  
  
  cProcessingQueue.async {
      //call that launches the c operation
  }
  </code></pre>
  <p>This keeps the UI responsive. However, on larger data sets this has the potential to throw crashes that contain statements like the following:</p>
  <pre><code>Action taken:    Process killed
  CPU:             48 seconds cpu time over 54 seconds (88% cpu average), exceeding limit of 80% cpu over 60 seconds
  </code></pre>
  <p>Is there  I can apply to have some kind of hard(ish) limit like &quot;<code>qos: .background</code> will always limit the usage to 50%&quot; in order to slow down the C lib execution in first place? I'm fine with using NSOperation or whatever there is but that would probably the most convenient solution.</p>
  <p>A few other ideas I can think of are:</p>
  <ol>
  <li>Feeding smaller chunks of data with some delay in between, however then we have arbitrary wait times that go unused</li>
  <li>Watching the CPU time as shown in <a href="https://stackoverflow.com/questions/44744372/get-cpu-usage-ios-swift">Get CPU usage IOS Swift</a> and modifying the C library to support halting executions</li>
  </ol>
  <p>but all in all, the &quot;thread-related limit&quot; would definitely the easiest solution out there.</p>