Add Timer.recordInterval method (#83)

* Add Timer.recordInterval method

Co-authored-by: Konrad `ktoso` Malawski <ktoso@apple.com>
This commit is contained in:
Moritz Lang 2020-10-12 21:18:21 +02:00 committed by GitHub
parent 5702ee1174
commit 44e8bfc7f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 29 additions and 0 deletions

View File

@ -12,6 +12,8 @@
//
//===----------------------------------------------------------------------===//
import Dispatch
// MARK: User API
extension Counter {

View File

@ -33,6 +33,15 @@ public extension Timer {
}
return try body()
}
/// Record the time interval (with nanosecond precision) between the passed `since` dispatch time and `end` dispatch time.
///
/// - parameters:
/// - since: Start of the interval as `DispatchTime`.
/// - end: End of the interval, defaulting to `.now()`.
func recordInterval(since: DispatchTime, end: DispatchTime = .now()) {
self.recordNanoseconds(end.uptimeNanoseconds - since.uptimeNanoseconds)
}
}
public extension Timer {

View File

@ -28,6 +28,7 @@ extension MetricsExtensionsTests {
("testTimerBlock", testTimerBlock),
("testTimerWithTimeInterval", testTimerWithTimeInterval),
("testTimerWithDispatchTime", testTimerWithDispatchTime),
("testTimerWithDispatchTimeInterval", testTimerWithDispatchTimeInterval),
("testTimerUnits", testTimerUnits),
("testPreferDisplayUnit", testPreferDisplayUnit),
]

View File

@ -78,6 +78,23 @@ class MetricsExtensionsTests: XCTestCase {
XCTAssertEqual(testTimer.values[4].1, 0, "expected value to match")
}
func testTimerWithDispatchTimeInterval() {
let metrics = TestMetrics()
MetricsSystem.bootstrapInternal(metrics)
let name = "timer-\(UUID().uuidString)"
let timer = Timer(label: name)
let start = DispatchTime.now()
let end = DispatchTime(uptimeNanoseconds: start.uptimeNanoseconds + 1000 * 1000 * 1000)
timer.recordInterval(since: start, end: end)
let testTimer = timer.handler as! TestTimer
XCTAssertEqual(testTimer.values.count, 1, "expected number of entries to match")
XCTAssertEqual(UInt64(testTimer.values.first!.1), end.uptimeNanoseconds - start.uptimeNanoseconds, "expected value to match")
XCTAssertEqual(metrics.timers.count, 1, "timer should have been stored")
}
func testTimerUnits() throws {
let metrics = TestMetrics()
MetricsSystem.bootstrapInternal(metrics)