Memory leak: steady increase in memory usage with simple device motion logging - ios

Consider this simple Swift code that logs device motion data to a CSV file on disk.
let motionManager = CMMotionManager()
var handle: NSFileHandle? = nil
override func viewDidLoad() {
super.viewDidLoad()
let documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let file = documents.stringByAppendingPathComponent("/data.csv")
NSFileManager.defaultManager().createFileAtPath(file, contents: nil, attributes: nil)
handle = NSFileHandle(forUpdatingAtPath: file)
motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {(data, error) in
let data_points = [data.timestamp, data.attitude.roll, data.attitude.pitch, data.attitude.yaw, data.userAcceleration.x,
data.userAcceleration.y, data.userAcceleration.z, data.rotationRate.x, data.rotationRate.y, data.rotationRate.z]
let line = ",".join(data_points.map { $0.description }) + "\n"
let encoded = line.dataUsingEncoding(NSUTF8StringEncoding)!
self.handle!.writeData(encoded)
})
}
I've been stuck on this for days. There appears to be a memory leak, as memory
consumption steadily increases until the OS suspends the app for exceeding resources.
It's critical that this app be able to run for long periods without interruption. Some notes:
I've tried using NSOutputStream and a CSV-writing library (CHCSVParser), but the issue is still present
Executing the logging code asynchronously (wrapping startDeviceMotionUpdatesToQueue in dispatch_async) does not remove the issue
Performing the sensor data processing in a background NSOperationQueue does fix the issue (only when maxConcurrentOperationCount >= 2). However, that causes concurrency issues in file writing: the output file is garbled with lines intertwined between each other.
The issue does not seem to appear when logging accelerometer data only, but does seem to appear when logging multiple sensors (e.g. accelerometer + gyroscope). Perhaps there's a threshold of file writing throughput that triggers this issue?
The memory spikes seem to be spaced out at roughly 10 second intervals (steps in the above graph). Perhaps that's indicative of something? (could be an artifact of the memory instrumentation infrastructure, or perhaps it's garbage collection)
Any pointers? I've tried to use Instruments, but I don't have the skills the use it effectively. It seems that the exploding memory usage is caused by __NSOperationInternal. Here's a sample Instruments trace.
Thank you.

First, see this answer of mine:
https://stackoverflow.com/a/28566113/341994
You should not be looking at the Memory graphs in the debugger; believe only what Instruments tells you. Debug builds and Release builds are memory-managed very differently in Swift.
Second, if there is still trouble, try wrapping the interior of your handler in an autoreleasepool closure. I do not expect that that would make a difference, however (as this is not a loop), and I do not expect that it will be necessary, as I suspect that using Instruments will reveal that there was never any problem in the first place. However, the autoreleasepool call will make sure that autoreleased objects are not given a chance to accumulate.

Related

FileHandle don't free memory in iOS

I'll send large file to server. The file will be separated to chunks. I receive high memory consumption when I call FileHandle.readData(ofLength:). Memory for chunk don't deallocate, and after some time I receive EOM exception and crash.
Profiler show problem in FileHandle.readData(ofLength:) (see screenshots)
func nextChunk(then: #escaping (Data?) -> Void) {
self.previousOffset = self.fileHandle.offsetInFile
autoreleasepool {
let data = self.fileHandle.readData(ofLength: Constants.chunkLength)
if data == Constants.endOfFile {
then(nil)
} else {
then(data)
self.currentChunk += 1
}
}
}
The allocations tool is simply showing you where the unreleased memory was initially allocated. It is up to you to figure out what you subsequently did with that object and why it was not released in a timely manner. None of the profiling tools can help you with that. They can only point to where the object was originally allocated, which is only the starting point for your research.
One possible problem might be if you are creating Data-based URLRequest objects. That means that while the associated URLSessionTask requests are in progress, the Data is held in memory. If so, you might consider using a file-based uploadTask instead. That prevents the holding the Data associated with the body of the request in memory.
Once your start using file-based uploadTask, that begs the question as to whether you need/want to break it up into chunks at all. A file-based uploadTask, even when sending very large assets, requires very little RAM at runtime. And, at some future point in time, you may even consider using a background session, so the uploads will continue even if the user leaves the app. The combination of these features may obviate the chunking altogether.
As you may have surmised, the autoreleasepool may be unnecessary. That is intended to solve a very specific problem (where one create and release autorelease objects in a tight loop). I suspect your problem rests elsewhere.

How do I tell what objects are specifically consuming all the memory/RAM in my iOS app?

Say I have an app and I notice it has high memory usage. How do I determine WHAT is taking up all the memory in terms of specific object(s). Can I do this through the Xcode Memory Debugger somehow? Instruments?
Take this code example:
class RootViewController: UIViewController {
var image: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let data = try! Data(contentsOf: URL(string: "https://effigis.com/wp-content/uploads/2015/02/Airbus_Pleiades_50cm_8bit_RGB_Yogyakarta.jpg")!)
self.image = UIImage(data: data)
}
}
The image at that URL is about 40 MB, and in this example contributes significantly to my app's large memory footprint.
How do I determine "Oh yeah, it's this UIImage right here taking up 40 MB of memory by itself!"
Short answer:
Unfortunately, there’s no simple “for this given large memory allocation, it is associated with this particular UIImage”. You can use stack traces, either in Instruments’ “Allocations” tool or the Xcode “Debug memory graph” (with “malloc stack” feature), to identify what was allocated where, but it’s exceedingly difficult to use this to track from some large malloc for the image data and the original UIImage object. For simple objects it works fine, but it’s a little more convoluted for for images.
Long answer:
The challenge with images is that that often the memory allocated for the image data is somewhat decoupled from the UIImage object itself. The allocation of the UIImage object is easily tracked back to where you instantiated it, but not the buffer for the data backing the image. Worse, when we supply this image to some image view, the stack trace for that image buffer will drop you into rendering engine call tree, not your code, making it even harder.
That having been said, using Instruments, you can often get clues about what’s going on. For example, using the “Allocations” tool, go to the list of allocations, and see what was allocated where. If you take that list, sort it by size, and you can see a stack trace, on the right, of where it was allocated:
Now in this case, I used the image in a UIImageView, and therefore the resulting allocation is buried inside the the iOS frameworks, not directly to our code. But one can infer from the stack trace that this was the result of rendering this JPG in the UI.
So, while you can’t easily conclude “oh, that’s the specific Airbus Pleiades image,” you can at least conclude that the particular allocation was associated with some JPG.
A few unrelated observations:
I suspect you were just keeping your example simple, but obviously you would never use Data(contentsOf:) from the main thread like that. Your UI will be blocked and you risk having your app killed by the watchdog process.
You'd generally initiate the network request asynchronously:
let url = URL(string: "https://effigis.com/wp-content/uploads/2015/02/Airbus_Pleiades_50cm_8bit_RGB_Yogyakarta.jpg")!
URLSession.shared.dataTask(with: url) { data, _, _ in
guard
let data = data,
let image = UIImage(data: data)
else {
return
}
DispatchQueue.main.async {
self.image = image
}
}.resume()
This not only avoids blocking the main thread, but you theoretically could use the URLResponse and Error parameters if you wanted any special handling for given errors (e.g. customized error messages in the UI or whatever).
When downloading large assets like this, if you don’t need to show the image in the UI immediately, you might use a download task instead, which has a much lower peak memory usage than Data(contentsOf:) or a dataTask:
let url = URL(string: "https://effigis.com/wp-content/uploads/2015/02/Airbus_Pleiades_50cm_8bit_RGB_Yogyakarta.jpg")!
let filename = url.lastPathComponent
URLSession.shared.downloadTask(with: url) { location, _, _ in
guard let location = location else { return }
do {
let folder = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("images")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
let fileURL = folder.appendingPathComponent(filename)
try FileManager.default.moveItem(at: location, to: fileURL)
} catch {
print(error)
}
}.resume()
If you do this, you won't require anything close to the 40mb during the download process. That might be critical if downloading lots of assets or if you’re not immediately showing the image in the UI. Also, if you later choose to use background URLSession, you can do this with download tasks, but not data tasks.
It’s worth noting that JPG images (and to a lesser degree, PNG images) are generally compressed. Thus, you can easily find that you might be downloading an asset whose size may be measured in kilobytes, but when you go to use it, will require megabytes. The general rule of thumb is that, regardless of the size of the file you use or the size of the control in which you’re using it, the memory required when you use the image is generally 4 × width × height (measured in pixels).
For example, a 5,494 × 5,839 px image may take up 122 mb (!) when you go to use it. The particulars may vary, but 4 × width × height is a good assumption. When considering memory consumption, the size of the file is a misleading indication of the amount of memory that might be used when you go to use this asset. Always consider the actual image dimensions because it’s going to be uncompressed when you use it.
In my answer above, I focused on Instruments’ Allocations tool. But it's worth noting that when diagnosing memory usage, the “Debug Memory Graph” feature is great when you’re trying to diagnose where the strong references are (great for identifying strong reference cycles). It’s not really relevant to this particular discussion, but can be useful if you’re tracking down where you used an image.
For example, here, I’ve downloaded your image (using URLSession) and not only set the image property of my view controller, but also used it in a UIImageView. This “Debug Memory Graph” tool is great for visualizing what is used where (but admittedly, not for correlating specific memory allocations to code):
I also editing my scheme’s diagnostic options to include the “malloc stack” feature, giving me the stack trace, on the right, like you see in the Allocations tool, above.
The Allocations instrument in Instruments can do this. Choosing Allocations List from the jump bar will show every memory allocation your app makes. Sort the table by allocation size to see the largest memory allocations.
What most developers are interested in is finding the code that allocates large amounts of memory. I answered that question at the following link:
Using instruments tool to locate leaks
I know the title of the question is about leaks, but the technique works the same for memory allocations.

Extremely high Memory & CPU usage when uploading parsed JSON data to Firebase in loop function

This is my very first question here so go easy on me!
I'm a newbie coder and I'm currently trying to loop through JSON, parse the data and backup the information to my Firebase server - using Alamofire to request the JSON information.
Swift 4, Alamofire 4.5.1, Firebase 4.2.0
The process works - but not without infinitely increasing device memory usage & up to 200% CPU usage. Through commenting out lines, I singled the memory and CPU usage down to the Firebase upload setValue line in my data pulling function - which iterates through a JSON database of unknown length (by pulling a max of 1000 rows of data at a time - hence the increasing offset values). The database that I'm pulling information from is huge, and with the increasing memory usage, the function grinds to a very slow pace.
The function detects if it's found an empty JSON (end of the results), and then either ends or parses the JSON, uploads the information to Firebase, increases the offset value by 1000 rows, and then repeats itself with the new offset value.
var offset: Int! = 0
var finished: Bool! = false
func pullCities() {
print("step 1")
let call = GET_CITIES + "&offset=\(self.offset!)&rows=1000"
let cityURL = URL(string: call)!
Alamofire.request(cityURL).authenticate(user: USERNAME, password: PASSWORD).responseJSON { response in
let result = response.result
print("step 2")
if let dict = result.value as? [Dictionary<String, Any>] {
print("step 3")
if dict.count == 0 {
self.finished = true
print("CITIES COMPLETE")
} else {
print("step 4")
for item in dict {
if let id = item["city"] as? String {
let country = item["country"] as? String
let ref = DataService.ds.Database.child("countries").child(country!).child("cities").child(id)
ref.setValue(item)
}
}
self.finished = false
print("SUCCESS CITY \(self.offset!)")
self.offset = self.offset! + 1000
}
}
if self.finished == true {
return
} else {
self.pullCities()
}
}
}
It seems to me like the data being uploaded to Firebase is being saved somewhere and not emptied once the upload completes? Although I couldn't find much information on this issue when searching through the web.
Things I've tried:
a repeat, while function (no good as I only want 1 active repetition of each loop - and still had high memory, CPU usage)
performance monitoring (Xcode call tree found that "CFString (immutable)" and "__NSArrayM" were the main reason for the soaring memory usage - both relating to the setValue line above)
memory usage graphing (very clear that memory from this function doesn't get emptied when it loops back round - no decreases in memory at all)
autoreleasepool blocks (as per suggestions, unsuccessful)
Whole Module Optimisation already enabled (as per suggestions, unsuccessful)
Any help would be greatly appreciated!
UPDATE
Pictured below is the Allocations graph after a single run of the loop (1,000 rows of data). It shows that what is likely happening is that Firebase is caching the data for every item in the result dict, but appears to only de-allocate memory as one whole chunk when every single upload has finished?
Ideally, it should be de-allocating after every successful upload and not all at once. If anyone could give some advice on this I would be very grateful!
FINAL UPDATE
If anyone should come across this with the same problem, I didn't find a solution. My requirements changed so I switched the code over to nodejs which works flawlessly. HTTP requests are also very easy to code for on javascript!
I had a similar issue working with data on external websites and the only way I could fix it was to wrap the loop in an autoreleasepool {} block which forced the memory to clear down on each iteration. Given ARC you might think such a structure is not needed in Swift but see this SO discussion:
Is it necessary to use autoreleasepool in a Swift program?
Hope that helps.
sometimes compiler is not able to properly optimise your code unless you enable whole module optimisation in project build settings. this is usually happening when generics is being used.
try to turn it on even for debug env and test.

Elusive crash: terminated due to memory issue

I'm still trying to debug an elusive crash in my app. See here for my earlier post.
The app takes sound from the microphone, processes it, and continuously updates the display with the processed results. After running uneventfully for many minutes, the app will halt with Message from debugger: terminated due to memory issue. There is no stack trace.
The timing of the crash makes it appear that there is some finite resource that gets exhausted after so many minute of running. The time it takes to crash is quite uniform. The time to crash may vary unpredictably when I change something in my code, but as long as the code stays the same, the time to crash keeps approximately the same. On a recent set of 10 test runs, the time to crash varied between 1014 seconds and 1029 seconds.
The number of times the display gets updated is even more uniform. On that same set of 10 tests, the number of calls to UIView.draw varied from 15311 to 15322. That's a variation of 0.07 percent, as opposed to 1.5 percent in the time to crash.
It's not running out of memory. My code is written in Swift 3, so I'm not doing any explicit mallocs or frees. I've made my class references weak where needed. And I've tested under the Activity Monitor, Allocations, and Leaks Instruments under XCode. My program takes up 44.6 MiB, and it doesn't grow with time.
And I've been careful about thread safety when accessing shared data. All shared data is read and written on the same serial DispatchQueue.
I've traced the crash to a section of code that writes a byte array to disk, then reads in another array of bytes. Here's a simplified version of that code:
var inputBuf:Buffer = Buffer()
var outputBuf: Buffer = Buffer()
var fileHandle:FileHandle? = ...
struct Buffer {
let bufferSize = 16384
var fileIndex:Int = 0
var bytes:[UInt8]
init() {
bytes = [UInt8](repeating:0, count:bufferSize)
}
func save(fileHandle:FileHandle) {
fileHandle.seek(toFileOffset: UInt64(Int64(fileIndex)))
fileHandle.write(Data(bytes))
}
}
func bug()
{
outputBuf.save(fileHandle:fileHandle!)
fileHandle!.seek(toFileOffset: UInt64(inputBuf.fileIndex))
let data = fileHandle!.readData(ofLength: inputBuf.bufferSize )
for i in 0..<data.count {
inputBuf.bytes[i] = data[i] // May crash here
}
}
Usually the crash occurs during the loop that copies data from the result of the readData to my buffer. But on one occasion, the loop completed before the crash. That leads me to suspect the actual crash occurs on another thread. There's no stack trace, so my only debugging technique is to insert print statements in the code.
fileIndex is always between 0 and 2592500. I modified the code to close the FileHandle after use and create a new FileHandle when next needed. It did not affect the outcome.
It was the zombie detector! I turned off zombie detection and the app runs forever.

iOS: Detect memory constraints before allocating objects

Is there a technique for avoiding undue memory consumption by testing the availability of memory before it's allocated? I understand that the general iOS approach is to optimize memory usage and respond to didReceiveMemoryWarning when necessary, but sometimes that doesn't cut it.
In my use case (image processing), I'm allocating space for a (potentially) large image using UIGraphicsBeginImageContext(). If the image is too big, I eventually get a didReceiveMemoryWarning. But, it's too late at that point: from a user experience perspective, it would've been better to prevent the user from working with such a large image to begin with; it would make more sense to say, "Sorry! Image size too big! Do something else!" before creating it than to say, "Ooops! Crashing now!"
I found a few SO threads on querying available memory and/or total physical memory, but using them is a messy and unreliable solution: there's no way to tell how much memory the OS is actually going to let you use at a given point in time, regardless of how much is free.
Basically, I want these semantics: (in "Swift-Java-ese")
try {
UIGraphicsBeginImageContext(CGRect(x: reallyBig, y: reallyBig))
}
catch NotEnoughMemoryException {
directUserToPickSmallerImage()
}
// The memory is mine; it's OK to use it
continueUsingBigImage()
Is there a methodology for doing this in iOS?
You might try pre-flitting with NSMutableData var length: Int and check for nil.
let data: NSMutableData? = NSMutableData(length:1000)
if data != nil {
println("Success")
}
else {
println("Failure")
}

Resources