Implement `static func measure(repeatCount:_:)`

This commit is contained in:
YOCKOW 2020-05-24 13:09:57 +09:00
parent bc0cfa3988
commit ecb0846476
No known key found for this signature in database
GPG Key ID: BEEDB9712A367313
2 changed files with 19 additions and 8 deletions

View File

@ -10,13 +10,9 @@ Its prototype is [YOCKOW's Gist](https://gist.github.com/YOCKOW/12d9607cb30f40b7
```Swift
import TimeSpecification
func time(_ body:() -> Void) {
let start = TimeSpecification(clock: .system)
body()
let end = TimeSpecification(clock: .system)
let duration = end - start
print("\(duration)")
}
let duration = TimeSpecification.measure(repeatCount: 100) { doIt() }
print("It took \(duration) seconds.") // -> Processing time to execute `doIt` 100 times.
```
### With `Date`
@ -25,7 +21,7 @@ func time(_ body:() -> Void) {
import TimeSpecification
let now = TimeSpecification(clock: .calendar)
let dateNow = Date(timeIntervalSince1970: now)
let dateNow = Date(timeIntervalSince1970: now) // -> Almost same with Date(timeIntervalSince1970: Double(time(nil)))
```

View File

@ -190,3 +190,18 @@ extension TimeSpecification {
self.init(c_timespec)
}
}
extension TimeSpecification {
/// Measure a processing time of the closure.
///
/// - parameters:
/// * repeatCount: Indicates the number of times to execute the closure. It must be greater than zero.
/// * body: The target closure.
public static func measure(repeatCount: Int = 1, _ body: () throws -> Void) rethrows -> TimeSpecification {
precondition(repeatCount > 0, "\(#function): `repeatCount` must be greater than zero.")
let start = TimeSpecification(clock: .system)
for _ in 0..<repeatCount { try body() }
let end = TimeSpecification(clock: .system)
return end - start
}
}