简体   繁体   中英

CPU and Memory usage of a method call in iPhone

I am trying to add some performance stats to a method call for my iPhone app. I used the following to find the time to process:

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

Are there similar strategies to measure CPU and memory usage of a method call?

Use Instruments to check your app's performance. Apple has done a pretty decent job, so no need to reinvent the wheel.

使用仪器在真实设备上实际使用这些测量。

You are going to have to do some work to get this working but here's how you can do it.

  • From this SO answer you can learn how to get the current CPU usage.
  • From this SO answer you can learn how to get the current Memory usage.

Now you can spawn a new thread that checks the CPU and memory periodically or on-demand, then create a class, something like this:

@interface ProfilerBlock
-(id) init;
-(void) end;
@end
  • The init method should initialize the current time and register the ProfilerBlock instance to get information from the worker thread about memory usage and CPU usage.
  • The end method should calculate the time and print all the needed information or write it to a file or something :)

Now create a C-Style releasing function for the ProfilerBlock class

static void __$_Profiler_Block_Release_Object_$__(ProfilerBlock **obj) // the long name is just to prevent duplicated symbol names //
{
    [(*obj) end];
    [(*obj) release];
    (*obj) = nil;
}

Finally you can create macros to make your life easier:

#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];

Once you have all this, you can profile methods like this:

-(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 //
}

I hope this helps, sorry if I didn't go in detail about how to meassure memory and CPU but I believe it is well covered in the other answers.

 NSTimeInterval t1 = [[NSDate date] timeIntervalSince1970];

.... custom processes ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM