One Quickie


BNRTimeBlock in Swift (Swift->General)
This blog post has a little snippet for timing a block. Here's a Swift version:
func BNRTimeBlock(_ block: @noescape () -> Void) -> TimeInterval {
    var info = mach_timebase_info()
    guard mach_timebase_info(&info) == KERN_SUCCESS else { return -1 }
    
    let start = mach_absolute_time()
    block()
    let end = mach_absolute_time()
    
    let elapsed = end - start
    
    let nanos = elapsed * UInt64(info.numer) / UInt64(info.denom)
    return TimeInterval(nanos) / TimeInterval(NSEC_PER_SEC)
}
And call it like
let time1 = BNRTimeBlock {
    print("groovy")
    // do other work.
}

print("    took (time1)")



borkware home | products | miniblog | rants | quickies | cocoaheads
Advanced Mac OS X Programming book

webmonster@borkware.com