手表
一个简单的计时器用来看记录两个时间戳之间的流逝时间,容易找出任何函数、代码块或异步回调的执行时间。
安装
Cocoapods
将以下行添加到您的项目Podfile中
pod 'Watches'
然后,在终端中运行 pod install
手动
将 Watches.swift
源代码文件拖放到您的项目中
使用方法
默认情况下,Watches 会自动以以下格式打印调试日志:
"\(identifier)的耗时为\(interval)"
如果您想禁用此自动日志功能,请设置:
Watches.printElapsedTimeAutomatically = false
追踪任何异步回调(如网络请求)的耗时,在调用异步任务之前使用特定标识符对时间进行点对点标注
Watches.tick("LoadProfile")
然后在异步回调闭包中调用 tock 对应的标识符
Watches.tock("LoadProfile")
例如使用 Alamofire
Watches.tick("LoadProfile")
Alamofire.request(loadProfileUrl).responseJSON { response in
Watches.tock("LoadProfile")
}
将按照默认格式打印耗时间隔
结果:LoadProfile的耗时为1.20113898515701
您可以根据需要提供自定义的格式
Watches.tock("LoadProfile") { debugPrint("花费时间 \($0) 的 \($1)") }
如果您自己的目的需要耗时间隔,从 tock 的返回值中获取
//You can disable auto print feature if you want
Watches.printElapsedTimeAutomatically = false
//Then get the result from tock function
let elapsedTime = Watches.tock("LoadProfile")
确定任何代码块的执行时间。
Watches.create("1 million times loop").tick {
//Block of code to measure
for _ in 0...10000000 { }
}.tock()
结果:1百万次循环的耗时为0.214788019657135
如果您需要自定义打印格式,只需提供 tock 回调闭包。
Watches.create("2 million times loop").tick {
//Block of code to measure
for _ in 0...20000000 { }
}.tock { debugPrint("Time for finishing \($0) is \($1)")}
结果:完成2百万次循环花费时间为0.411646008491516
如果您只想要结果
let executionTime = Watches.create("MyClosure").tick {
//Block of code to measure
sleep(3)
}.tock()
debugPrint(executionTime)
结果:3.0011550188064575
许可
Watches 采用 MIT 许可协议发布。有关详细信息,请参阅 LICENSE 文件。版权所有Vuong Huu Tai。