【问题标题】:CPU and Memory usage of a method call in iPhoneiPhone中方法调用的CPU和内存使用情况
【发布时间】:2013-04-04 00:51:33
【问题描述】:

我正在尝试将一些性能统计信息添加到我的 iPhone 应用程序的方法调用中。我使用以下方法来查找处理时间:

#define TICK   NSDate *startTime = [NSDate date]
#define TOCK   NSLog(@"Time to process: %f", -[startTime timeIntervalSinceNow])

是否有类似的策略来衡量方法调用的 CPU 和内存使用情况?

【问题讨论】:

  • 那个连字符在那里做什么? (..., -[startTime timeIntervalSinceNow]))
  • 取反返回值。

标签: ios objective-c memory cpu-usage


【解决方案1】:

您将不得不做一些工作才能使其正常工作,但您可以这样做。

  • 通过这个 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,但我相信其他答案已经很好地涵盖了这一点。

【讨论】:

    【解决方案2】:

    使用Instruments 检查您应用的性能。 Apple 做得相当不错,因此无需重新发明轮子。

    【讨论】:

    • 实际上,随着时间的推移在许多环境中跟踪大粒度任务的执行时间具有很大的价值。必须使用 Instruments 总是让人望而却步。
    【解决方案3】:
     NSTimeInterval t1 = [[NSDate date] timeIntervalSince1970];
    

    ....自定义流程...

     NSTimeInterval t2 = [[NSDate date] timeIntervalSince1970];
     NSTimeInterval dt = t2-t1; this is in milisec;
    

    【讨论】:

      【解决方案4】:

      使用 Instruments 在现实生活中的设备上进行这些测量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多