是否有一种方法可以确定一个方法需要执行多少时间(以毫秒为单位)?


当前回答

好吧,如果你的目标是找出你可以修复什么使它更快,那是一个有点不同的目标。测量函数所花费的时间是一种很好的方法,可以发现您所做的事情是否产生了影响,但要找出该做什么,您需要一种不同的技术。这就是我的建议,我知道你可以在iphone上这么做。

编辑:审稿人建议我详细说明答案,所以我想用一种简单的方式来解释。 你的整个程序需要足够的时钟时间来打扰你。假设这是N秒。 你假设你可以加速它。唯一的方法就是让它在这段时间内不做它正在做的事情,占m秒。 你一开始并不知道这个东西是什么。您可以像所有程序员一样猜测,但它很容易是其他东西。不管是什么,下面是找到它的方法:

因为那个东西,不管它是什么,占了m/N的时间,这意味着如果你随机暂停它,你在它做那件事的时候抓住它的概率是m/N。当然,它可能在做其他事情,但暂停它,看看它在做什么。 现在再做一次。如果你看到它再次做同样的事情,你就更可疑了。

做10次,或者20次。现在,如果你看到它在多次暂停中做一些特定的事情(不管你怎么描述它),你可以摆脱,你知道两件事。你大概知道需要花多少时间,但你很清楚要修复什么。 如果你还想知道能节省多少时间,那很简单。之前测量,修正,之后测量。如果你真的很失望,那就退出修复。

你知道这和测量有什么不同吗?这是发现,而不是测量。大多数分析都是基于尽可能精确地测量所花费的时间,就好像这很重要一样,并明确需要解决的问题。剖析并不能找到所有的问题,但是这种方法确实能找到所有的问题,而那些你没有找到的问题对你造成了伤害。

其他回答

我在我的utils库中使用这个(Swift 4.2):

public class PrintTimer {
    let start = Date()
    let name: String

    public init(file: String=#file, line: Int=#line, function: String=#function, name: String?=nil) {
        let file = file.split(separator: "/").last!
        self.name = name ?? "\(file):\(line) - \(function)"
    }

    public func done() {
        let end = Date()
        print("\(self.name) took \((end.timeIntervalSinceReferenceDate - self.start.timeIntervalSinceReferenceDate).roundToSigFigs(5)) s.")
    }
}

…然后调用如下方法:

func myFunctionCall() {
    let timer = PrintTimer()
    // ...
    timer.done()
}

…运行后在控制台中看起来是这样的:

MyFile.swift:225 - myFunctionCall() took 1.8623 s.

虽然不像上面的TICK/TOCK那样简洁,但它足以清楚地看到它在做什么,并自动包括正在计时的内容(通过文件、方法开头的行和函数名)。显然,如果我想要更多的细节(例如,如果我不只是计时一个方法调用,因为是通常的情况下,而是在该方法内计时块),我可以在PrintTimer init上添加“name="Foo""参数来命名它除了默认值之外的东西。

NSDate *methodStart = [NSDate date];

/* ... Do whatever you need to do ... */

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

迅速:

let methodStart = NSDate()

/* ... Do whatever you need to do ... */

let methodFinish = NSDate()
let executionTime = methodFinish.timeIntervalSinceDate(methodStart)
print("Execution time: \(executionTime)")

Swift3:

let methodStart = Date()

/* ... Do whatever you need to do ... */

let methodFinish = Date()
let executionTime = methodFinish.timeIntervalSince(methodStart)
print("Execution time: \(executionTime)")

易于使用,具有亚毫秒精度。

我使用非常少的,一页的类实现,灵感来自这篇博客文章的代码:

#import <mach/mach_time.h>

@interface DBGStopwatch : NSObject

+ (void)start:(NSString *)name;
+ (void)stop:(NSString *)name;

@end

@implementation DBGStopwatch

+ (NSMutableDictionary *)watches {
    static NSMutableDictionary *Watches = nil;
    static dispatch_once_t OnceToken;
    dispatch_once(&OnceToken, ^{
        Watches = @{}.mutableCopy;
    });
    return Watches;
}

+ (double)secondsFromMachTime:(uint64_t)time {
    mach_timebase_info_data_t timebase;
    mach_timebase_info(&timebase);
    return (double)time * (double)timebase.numer /
        (double)timebase.denom / 1e9;
}

+ (void)start:(NSString *)name {
    uint64_t begin = mach_absolute_time();
    self.watches[name] = @(begin);
}

+ (void)stop:(NSString *)name {
    uint64_t end = mach_absolute_time();
    uint64_t begin = [self.watches[name] unsignedLongLongValue];
    DDLogInfo(@"Time taken for %@ %g s",
              name, [self secondsFromMachTime:(end - begin)]);
    [self.watches removeObjectForKey:name];
}

@end

它的用法很简单:

调用[DBGStopwatch start:@"slow-operation"];一开始 然后[DBGStopwatch stop:@"slow-operation"];做完之后,才能得到时间

我用这个:

clock_t start, end;
double elapsed;
start = clock();

//Start code to time

//End code to time

end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
NSLog(@"Time: %f",elapsed);

但我不确定iPhone上的CLOCKS_PER_SEC。你还是别打了吧。

既然你想优化时间从一个页面移动到另一个UIWebView,这是不是意味着你真的在寻找优化Javascript加载这些页面?

为此,我想看看WebKit分析器,就像这里所说的:

http://www.alertdebugging.com/2009/04/29/building-a-better-javascript-profiler-with-webkit/

另一种方法是从高层次开始,思考如何设计有问题的网页,使用AJAX样式的页面加载来最小化加载时间,而不是每次都刷新整个web视图。