How to start/stop Instruments (Time Profiler) prog

2019-06-07 17:36发布

问题:

Is there any way to start/stop Instruments profiling programmatically ? I need to profile just a specific section of my OS X code in a reliable way but I can't seem to find any documentation for Instruments which might tell me how I might do this. With CHUD/Shark there was a programming API and a command line tool to support this but I don't see the equivalent for Instruments anywhere ? FWIW I found some old forum posts from around 2009 bemoaning the lack of Instruments functionality in this area but nothing more recent.

回答1:

Yes. Look for DTPerformanceSession. It was introduced with Instruments 4.0. It was enhanced in Instruments 4.1.

Those documents provide this sample code:

CFStringRef process = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"), getpid());
CFErrorRef error = NULL;
DTPerformanceSessionRef session = DTPerformanceSessionCreate(NULL, process, NULL, &error);
DTPerformanceSessionAddInstrument(session, (CFStringRef)@DTPerformanceSession_TimeProfiler, NULL, NULL, &error);
CFMutableArrayRef instrumentIDs = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
CFArrayAppendValue(instrumentIDs, @DTPerformanceSession_TimeProfiler);
DTPerformanceSessionStart(session, instrumentIDs, &error);

// do something in your app

DTPerformanceSessionStop(session, instrumentIDs, &error);
DTPerformanceSessionSave(session, (CFStringRef)@"/tmp/myAppProfile", &error);
DTPerformanceSessionDispose(session, &error);