问题
When my loop runs for about 15k times too much CPU is being used. It's in the range of 90 -100 % always. What I am doing inside the loop is a series of Core data entity updating/creation. Why does that happen? I am running my process in background and I have specified the thread priority to minimum value too!
回答1:
Paul R is correct - the system will achieve the tasks in the loop as quickly as possible given the resources it has. In this case, it is manipulating Core Data objects in the Managed Object Context and not committing to disk so the only limitation to how fast it can execute is CPU Time.
Is this causing a UI thread issue? Theoretically, if the UI thread wants CPU time, it should take it. The sleep() would fix that, but is inideal because your background task would take longer to complete.
If so, is there a way to break out the work so it can be more simply chunked than a 15k item loop?
Is something in the loop running using mutex / @synchronise? This can cause a delay before it will ramp down it's CPU-time when requested which can translate to laggy UI.
来源:https://stackoverflow.com/questions/11828567/cpu-usage-shooting-up-when-i-am-running-a-for-in-loop-os-x-app