5

Is it possible to setup an Instruments run programmatically from my code? For instance, I'd like to structure my code something like this where startTrace might setup a specific probe for the current thread and start recording while stopTrace would stop recording. I would be writing the content of those routines using the Instruments API that is the subject of this question.

-(void)myInterestingMethod
{
    [self startTrace];

    // do something interesting and performance critical

    [self stopTrace];
}

If the above isn't available, is setting up my own DTrace probe a viable alternative?

nall
  • 15,899
  • 4
  • 61
  • 65
  • libdtrace could be an option but I’m not sure the API is documented. –  Jan 22 '11 at 07:45
  • We can now use "points of interest". See http://stackoverflow.com/a/39416673/1271826. – Rob Sep 09 '16 at 18:41

1 Answers1

5

Doesn't look like there's anything straight-forward, but there is an instruments command-line tool. Here's some quick+dirty code that will invoke it and sample CPU usage for the calling process

static void sampleMe() {
    // instruments -t '/Developer/Applications/Instruments.app/Contents/Resources/templates/CPU Sampler.tracetemplate' -p 26838 -l 5000

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/usr/bin/instruments"];
    [task setArguments:[NSArray arrayWithObjects:
                        @"-t",
                        @"/Developer/Applications/Instruments.app/Contents/Resources/templates/CPU Sampler.tracetemplate",
                        @"-p",
                        [NSString stringWithFormat:@"%ld", getpid()],
                        @"-l",
                        @"5000",
                        nil]];
    [task setCurrentDirectoryPath:NSHomeDirectory()];
    [task setStandardInput:[NSPipe pipe]];
    [task setStandardOutput:[NSPipe pipe]];
    [task setStandardError:[NSPipe pipe]];
    [task launch];
    // purposely leak everything since I can't be bothered to figure out lifetimes
}

After invocation a file named instrumentscli0.trace will be in your home directory.

Update: Instruments 4.0 offers DTSendSignalFlag in the DTPerformanceSession for iOS apps.

rentzsch
  • 3,548
  • 4
  • 27
  • 39
  • 1
    +1 for "// purposely leak everything since I can't be bothered to figure out lifetimes" – Barjavel Aug 07 '12 at 11:05
  • 1
    Note: It appears that DTPerformanceSession only works on the simulator. This is not useful for me because I only care about the device's performance profile. – Jacob Jennings Dec 26 '12 at 22:01