简体   繁体   English

我如何针对优化目的来分析一段代码在Objective-C / Cocoa中执行所需的时间

[英]How do I profile how long a piece of code takes to execute in Objective-C/Cocoa for optimization purposes

Lets say I've got two interchangeable pieces of code and I want to figure out which one of them takes less processor time to execute. 可以说我有两段可互换的代码,我想找出其中的哪一部分需要更少的处理器时间来执行。 How would I do this? 我该怎么做?

To get a very rough estimation I could just put NSLog() calls on either side of the code I wanted to profile, but it seems like the processor being otherwise very busy could skew the results. 为了得到一个非常粗略的估计,我可以将NSLog()调用放在要分析的代码的任何一侧,但是似乎处理器非常繁忙可能​​会使结果产生偏差。

Unless one of these two pieces of code is already in your app, and you've already profiled your app's overall performance to determine that the existing code is a major bottleneck, then what you're doing is called "premature optimization." 除非您的应用程序中已经包含这两段代码之一, 并且您已经分析了应用程序的整体性能以确定现有代码是主要瓶颈,否则您所做的就是“过早优化”。

Xcode includes an excellent profiler tool called " Shark ." Xcode包含了一个出色的探查工具“ Shark” For some versions, it's found in /Developer/Applications; 对于某些版本,可以在/ Developer / Applications中找到它。 for others, it's in a "Performance Tools" subdirectory. 对于其他用户,它位于“性能工具”子目录中。

Shark will tell you exactly how much time, as a percentage of overall execution time, your app is spending in each part of your code. Shark会准确告诉您您的应用在代码的每个部分中花费了多少时间(占总执行时间的百分比)。 The idea of using a tool like Shark is to follow the "80/20 rule" - your app will spend 80% of its time running 20% of its code, so for the best results you should spend 80% of your time optimizing that same 20%. 使用像鲨鱼的工具的思路是遵循“80/20法则” -您的应用程序将花费其80%的时间运行其代码的20%,所以为了达到最佳效果,你应该花80% 时间是优化相同的20%。

So, to answer your question directly, assuming that you have run Shark, and you're looking to optimize the topmost bottleneck, simply replace it with your optimized code and run your app under Shark again. 因此,假设您已经运行了Shark,并且想优化最顶层的瓶颈,则直接回答您的问题,只需将其替换为优化的代码,然后在Shark下再次运行您的应用程序即可。 Then, compare the percentage of the overall time being spent in the replacement code to that of the original. 然后,将替换代码中花费的总时间与原始代码中所花费的总时间的百分比进行比较。

Woo shark, yay. 乌鲨,是的。 See also Shark Remote Control . 另请参阅Shark遥控器 Basically, choose Sampling > Programmatic (Remote) from the menu in shark, then call chudStartRemotePerfMonitor and chudStopRemotePerfMonitor() bracketing the specific code you want to profile. 基本上,从shark的菜单中选择“ Sampling > Programmatic (Remote) ”,然后调用chudStartRemotePerfMonitor和chudStopRemotePerfMonitor(),将要分析的特定代码括起来。

That aside, here's a chunk of code I keep around for timing. 除此之外,这是我为了计时而保留的一大堆代码。

First the usage 首先用法

uint64_t startTime, stopTime;
startTime = mach_absolute_time();

< work to time goes here >

stopTime = mach_absolute_time();
logMachTime_withIdentifier_(stopTime - startTime, @"10000000 class messages");

and here's the helper function, logMachTime_withIdentifier_ . 这是帮助函数logMachTime_withIdentifier_

#import <mach/mach_time.h>
void logMachTime_withIdentifier_(uint64_t machTime, NSString *identifier) {
    static double timeScaleSeconds = 0.0;
    if (timeScaleSeconds == 0.0) {
        mach_timebase_info_data_t timebaseInfo;
        if (mach_timebase_info(&timebaseInfo) == KERN_SUCCESS) {    // returns scale factor for ns
            double timeScaleMicroSeconds = ((double) timebaseInfo.numer / (double) timebaseInfo.denom) / 1000;
            timeScaleSeconds = timeScaleMicroSeconds / 1000000;
        }
    }

    NSLog(@"%@: %g seconds", identifier, timeScaleSeconds*machTime);
}

Assuming you want to profile a whole app (not just a snippet of code), and that your app is written in C/C++/Objective-C (not, eg Ruby), and that you're using Xcode 3.0 or higher, you should also check out the Instruments application. 假设您要分析整个应用程序(不只是一小段代码),并且您的应用程序是用C / C ++ / Objective-C(不是Ruby)编写的,并且您使用的是Xcode 3.0或更高版本,还应检出“仪器”应用程序。 The "Sampler" instrument will give you very similar information to Shark (though without Shark's sometimes very helpful tips on improving performance). “ Sampler”仪器将为您提供与Shark非常相似的信息(尽管没有Shark有时会提供有关提高性能的非常有用的提示)。 In addition, you can track other resource utilization (GC, Core Data, network, disk I/O, etc.) that may be more important determinants of your app's performance than code efficiency (again, depending on the application). 此外,您可以跟踪其他资源利用率(GC,核心数据,网络,磁盘I / O等),这些资源可能是决定应用程序性能的重要因素,而不是代码效率(同样取决于应用程序)。 Instruments can also make use of the DTrace support in OS X 10.5 ( man dtrace ). 仪器还可以使用OS X 10.5( man dtrace )中的DTrace支持。 You can write your own instruments using DTrace to monitory your application more specifically (eg calls to one or more methods). 您可以使用DTrace编写自己的工具,以更具体地监视应用程序(例如,调用一个或多个方法)。

Using NSLog is a bad idea, as you suspect, because it likely makes use of the Apple System Logging system. 您怀疑,使用NSLog是一个坏主意,因为它可能利用了Apple System Logging系统。 There's a non-deterministic delay in writting a log to the asl and it showing up in the console. 将日志写入asl并显示在控制台中存在不确定的延迟。 I'm not sure when the timestamp is set. 我不确定何时设置时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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