diff --git a/README.md b/README.md index 1c5d97f..fc7a155 100644 --- a/README.md +++ b/README.md @@ -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))) ``` diff --git a/Sources/TimeSpecification/TimeSpecification.swift b/Sources/TimeSpecification/TimeSpecification.swift index d0f9e3c..05821a2 100644 --- a/Sources/TimeSpecification/TimeSpecification.swift +++ b/Sources/TimeSpecification/TimeSpecification.swift @@ -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..