usleep eating a large amount of CPU time, thread priorities weird

Originator:ewmailing
Number:rdar://8857757 Date Originated:2011-01-12
Status:Open Resolved:
Product:iOS Product Version:3.1-4.2
Classification:Performance Reproducible:Always
 
Summary:
On iOS devices (iPhone and iPad), calling usleep() consumes a significantly large amount of CPU time when on a background thread. usleep generally should be nicer to the processor.

In the open source library ALmixer (attached), there is a worker thread that is created to do some state management bookkeeping. Often, it does not need to actually do anything, so to be nice to the processor, I call usleep(10) to yield the thread. This works on all other systems I've tried (Mac OS, Windows, Linux, FreeBSD), but on iOS, I discovered that a large amount of time is being spent in usleep.

For programs that are near maxing out the CPU, this usleep() causes a pathological performance problem. Applications begin to start stuttering as it seems that this background thread keeps waking up.

To work around the problem, I change the pthread priority. I discovered that the default was 31 which is the highest or next highest priority. To improve the performance of my program, I had to lower the priority all the way to the lowest (0 I think). Small values above the lowest did not improve the performance.


Steps to Reproduce:
Attached is a demo program. It is a simple OpenGL template that activates my background thread. Run the app on a device in Instruments with the Time Profiler. You will see a huge amount of time spent in usleep() called on my worker thread.

There is not enough stuff going on in this program to see stuttering. If you could find a stressful program, you would probably see stuttering.


Expected Results:
usleep should not be sucking up all the CPU.

Actual Results:
CPU is eaten by usleep.

Regression:
Seems to always have been bad.

Notes:
In ALmixer.c, look for:
#if 0 // DISABLED FOR APPLE BUG DEMONSTRATION

If you enable this, you'll enable my thread priority code which sets the level to 0 and the CPU cost goes down significantly.

Also attached is a saved Instruments trace.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!