swift iOS / OSX / Swift中的精确计时
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift iOS / OSX / Swift中的精确计时相关的知识,希望对你有一定的参考价值。
//: Playground - noun: a place where code can play
import UIKit
//Most precise time keeper
// for more information on the benchmarks go to www.kandelvijaya.com
func timeBlockWithMach(_ block: () -> 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)
}
func test() {
let rtDate = timeBlockWithMach{
NSDate().timeIntervalSince1970
}
let rtMedia = timeBlockWithMach {
CACurrentMediaTime()
}
let rtAbsolute = timeBlockWithMach {
CFAbsoluteTimeGetCurrent()
}
var time = timeval()
let rtTimeOfDay = timeBlockWithMach {
gettimeofday(&time, nil)
}
let rtTimeWithMach = timeBlockWithMach {
mach_absolute_time()
}
let rtTimeWithProcessInfo = timeBlockWithMach {
ProcessInfo.processInfo.systemUptime
}
}
test()
// MARK: - Other timing functions
func timeBlockWithDateTime(_ block: () -> Void) -> TimeInterval {
let start = NSDate().timeIntervalSince1970
block()
let end = NSDate().timeIntervalSince1970
return end - start
}
func timeBlockWithCAMediaTiming(_ block: () -> Void) -> TimeInterval {
let start = CACurrentMediaTime()
block()
let end = CACurrentMediaTime()
return end - start
}
func timeBlockWithCFTime(_ block: () -> Void) -> TimeInterval {
let start = CFAbsoluteTimeGetCurrent()
block()
let end = CFAbsoluteTimeGetCurrent()
return end - start
}
func timeBlockWithGetTimeOfDay(_ block: () -> Void) -> TimeInterval {
var start = timeval()
gettimeofday(&start, nil)
block()
var end = timeval()
gettimeofday(&end, nil)
return Double(start.tv_usec - end.tv_usec)
}
以上是关于swift iOS / OSX / Swift中的精确计时的主要内容,如果未能解决你的问题,请参考以下文章
python Swift iOS和OSX的Web爬虫
Swift 特殊关键字
swift 构建OSX拖放操场:将dragndrop.swift抛出到共享源中,然后测试单个playgro中的示例
OSX Swift 在默认浏览器中打开 URL
Apple Swift学习教程
swift 雨燕 新手教程