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


当前回答

下面是我使用的两个单行宏:

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

像这样使用它:

TICK;

/* ... Do Some Work Here ... */

TOCK;

其他回答

我使用这个代码:

#import <mach/mach_time.h>

float TIME_BLOCK(NSString *key, void (^block)(void)) {
    mach_timebase_info_data_t info;
    if (mach_timebase_info(&info) != KERN_SUCCESS)
    {
        return -1.0;
    }

    uint64_t start = mach_absolute_time();
    block();
    uint64_t end = mach_absolute_time();
    uint64_t elapsed = end - start;

    uint64_t nanos = elapsed * info.numer / info.denom;
    float cost = (float)nanos / NSEC_PER_SEC;

    NSLog(@"key: %@ (%f ms)\n", key, cost * 1000);
    return cost;
}

这里有另一种方法,在Swift中,使用defer关键字来做到这一点

func methodName() {
  let methodStart = Date()
  defer {
    let executionTime = Date().timeIntervalSince(methodStart)
    print("Execution time: \(executionTime)")
  }
  // do your stuff here
}

来自苹果的文档:defer语句用于在将程序控制权转移到该defer语句出现的范围之外之前执行代码。

这类似于try/finally块,优点是将相关代码分组。

我使用基于Ron的解决方案的宏。

#define TICK(XXX) NSDate *XXX = [NSDate date]
#define TOCK(XXX) NSLog(@"%s: %f", #XXX, -[XXX timeIntervalSinceNow])

对于代码行:

TICK(TIME1);
/// do job here
TOCK(TIME1);

我们将在控制台中看到如下内容:TIME1: 0.096618

这里有一个Swift 3的解决方案,可以在任何地方对代码进行等分,以找到长时间运行的进程。

var increment: Int = 0

var incrementTime = NSDate()

struct Instrumentation {
    var title: String
    var point: Int
    var elapsedTime: Double

    init(_ title: String, _ point: Int, _ elapsedTime: Double) {
        self.title = title
        self.point = point
        self.elapsedTime = elapsedTime
    }
}

var elapsedTimes = [Instrumentation]()

func instrument(_ title: String) {
    increment += 1
    let incrementedTime = -incrementTime.timeIntervalSinceNow
    let newPoint = Instrumentation(title, increment, incrementedTime)
    elapsedTimes.append(newPoint)
    incrementTime = NSDate()
}

用法:-

instrument("View Did Appear")

print("ELAPSED TIMES \(elapsedTimes)")

样例输出:

[MyApp.SomeViewController.]仪器仪表(标题:“开始视图 Did Load", point: 1, elapsedTime: 0.040504038333892822), MyApp.SomeViewController。检测(标题:“完成添加 SubViews", point: 2, elapsedTime: 0.010585010051727295), MyApp.SomeViewController。仪器仪表(标题:“视图已出现”, 点:3,elapsedTime: 0.56564098596572876)]

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)")

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