您将不得不做一些工作才能使其正常工作,但您可以这样做。
- 通过这个 SO answer,您可以了解如何获取当前的 CPU 使用率。
- 通过此 SO answer,您可以了解如何获取当前的内存使用情况。
现在您可以生成一个新线程来定期或按需检查 CPU 和内存,然后创建一个类,如下所示:
@interface ProfilerBlock
-(id) init;
-(void) end;
@end
-
init 方法应该初始化当前时间并注册 ProfilerBlock 实例以从工作线程获取有关内存使用和 CPU 使用的信息。
-
end 方法应该计算时间并打印所有需要的信息或将其写入文件或其他东西:)
现在为 ProfilerBlock 类创建一个 C-Style 释放函数
static void __$_Profiler_Block_Release_Object_$__(ProfilerBlock **obj) // the long name is just to prevent duplicated symbol names //
{
[(*obj) end];
[(*obj) release];
(*obj) = nil;
}
最后,您可以创建宏来让您的生活更轻松:
#define CONCAT2(x, y) x ## y
#define CONCAT(x, y) CONCAT2(x, y)
#define PROFILER_SCOPE_OBJECT __attribute__((cleanup(__$_Profiler_Block_Release_Object_$__)))
#define PROFILE_BLOCK ProfilerBlock *CONCAT(__profilerBlock_, __LINE__) PROFILER_SCOPE_OBJECT = [[ProfilerBlock alloc] init];
一旦你拥有了所有这些,你就可以像这样分析方法:
-(void) methodToProfile
{
PROFILE_BLOCK
// add some code to profile here //
// the "end" function will get called automatically after the method is done, even if you return early, allowing you to process the profiled data //
}
我希望这会有所帮助,很抱歉,如果我没有详细介绍如何测量内存和 CPU,但我相信其他答案已经很好地涵盖了这一点。