我在使用CoreML预测时遇到了内存泄漏问题(应用程序的内存只会增加)。我找不到任何文档或示例来告诉我应该释放什么。在我的实际项目中,我禁用了ARC,但在本例中没有禁用(所以编译器不允许我手动释放任何东西,所以我猜我尝试过的东西不需要它)。
我已经将其简化为GitHub上的一个最小化案例。但这里是它的99%(该存储库仅包含模型和额外的项目资产,以及更多的错误检查 – 没有错误,预测运行良好,但为了stackoverflow而简化)。
#import <Cocoa/Cocoa.h>#import "SsdMobilenet.h"#include <string>#include <iostream>uint8_t ImageBytes[300*300*4];CVPixelBufferRef MakePixelBuffer(size_t Width,size_t Height){ auto* Pixels = ImageBytes; auto BytesPerRow = Width * 4; CVPixelBufferRef PixelBuffer = nullptr; auto Result = CVPixelBufferCreateWithBytes( nullptr, Width, Height, kCVPixelFormatType_32BGRA, Pixels, BytesPerRow, nullptr, nullptr, nullptr, &PixelBuffer ); return PixelBuffer;}int main(int argc, const char * argv[]){ auto* Pixels = MakePixelBuffer(300,300); SsdMobilenet* ssd = nullptr; for ( auto i=0; i<10000; i++ ) { if ( !ssd ) { ssd = [[SsdMobilenet alloc] init]; } auto* Output = [ssd predictionFromPreprocessor__sub__0:Pixels error:nullptr]; } return 0;}
有什么东西我应该清除、释放、解除分配的吗?我尝试过在每次迭代中释放ssd并重新创建它,但这没有帮助。
在HighSierra 10.13.6,xcode 10.1(10B61)上测试。
内存泄漏发生在2011年的iMac上(没有Metal,CPU执行)和2013年的Retina MBP上(在GPU上运行),以及其他模型,不仅仅是SSDMobileNet。
编辑1:使用Instruments的Generations/Snapshots功能进行查看,确实看起来是输出在泄漏,但我无法dealloc
或release
它,所以可能还有其他什么我需要做来释放结果?<non-object>
都是在CoreML深层内部的apply_convulution_layer()
调用中的分配。
回答:
感谢@用户,使用NSAutoReleasePool
并禁用ARC,这样就不会发生泄漏。(我也可以自动释放SSD,但这种特定的组合可以保持预先分配的SSD持久)。
对于启用ARC/自动引用计数的构建,我还没有解决方案,因为NSAutoReleasePool
不可用。
int main(int argc, const char * argv[]){ auto* Pixels = MakePixelBuffer(300,300); SsdMobilenet* ssd = [[SsdMobilenet alloc] init]; //SsdMobilenet* ssd = nullptr; for ( auto i=0; i<10000; i++ ) { NSAutoreleasePool* pool= [[NSAutoreleasePool alloc]init]; if ( !ssd ) { ssd = [[SsdMobilenet alloc] init]; } auto* Output = [ssd predictionFromPreprocessor__sub__0:Pixels error:nullptr]; //[Output release]; //[ssd release]; //ssd = nullptr; [pool drain]; } return 0;}