NSURLSessionDataTask causes high CPU usage
I use NSURLSessionDataTask
to stream data to an audio stream in the background (in this case it is not very important).
The problem I'm running into only happens with the boot code - I have isolated this and just dropped the data so no other parts of the system affect it.
I noticed that if I build NSURLSession
with config ( NSURLSessionConfiguration
) created with backgroundSessionConfigurationWithIdentifier
then the CPU usage at boot will be low (<5%). While this works (95% of the time), I believe it is not a supported configuration. I also need this to work when the app is in the foreground.
So instead I create NSURLSession
with the config created with ephemeralSessionConfiguration
, this also stops it using disk as background cache and so the smallest cpu should be used. However, in this scenario, the CPU uses rockets up to 70% and 80%.
The same cpu usage also happens with a configuration created with defaultSessionConfiguration
or even shared NSURLSession
with [NSURLSession sharedSession]
.
The data bandwidth does not change between each script - it just does not run in the background, resulting in high CPU usage.
I am on iOS 9.1 using SDK 9.1. This happens both in the simulator and on the device.
Update November 16 . As George pointed out, the didReceiveData method appears. The only way I have come across is to add a call
[NSThread sleepForTimeInterval:0.25];
which seems pretty sharp, but when loaded, the CPU gets around 60-80%, up to about 10-12%. The download is done in its own thread, so only the download that slows down. In fact, it doesn't slow down very much - it didReceiveData
just gets data in much larger chunks. It doesn't matter in my application.
You should probably delegateQueue
NSURLSession
queue with a low priority (i.e. dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
). My guess is that the problem is not that the processing actually takes up more CPU, but that it happens more often, the queue to which it is sent has a high priority.