Motivation: As discussed in Issue #28, there are a few preferred lightweight APIs for getting timestamps such as `DispatchTime` but those APIs return `UInt64` types, which need to be handled for overflow. Modifications: Added a generic `BinaryInteger` overload method for `recordNanoseconds` that guards against accidental overflows from `UInt64` to `Int64` Result: Users now have access to a new method to record nanosecond measurements with `Timer` that guards against overflows.
This commit is contained in:
parent
e4883dab79
commit
8e5110dcd6
|
|
@ -267,6 +267,15 @@ public class Timer {
|
|||
self.handler.recordNanoseconds(duration)
|
||||
}
|
||||
|
||||
/// Record a duration in nanoseconds.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - value: Duration to record.
|
||||
@inlinable
|
||||
public func recordNanoseconds<DataType: BinaryInteger>(_ duration: DataType) {
|
||||
self.recordNanoseconds(duration >= Int64.max ? Int64.max : Int64(duration))
|
||||
}
|
||||
|
||||
/// Record a duration in microseconds.
|
||||
///
|
||||
/// - parameters:
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ public extension Timer {
|
|||
func record(_ duration: DispatchTimeInterval) {
|
||||
switch duration {
|
||||
case .nanoseconds(let value):
|
||||
self.recordNanoseconds(Int64(value))
|
||||
self.recordNanoseconds(value)
|
||||
case .microseconds(let value):
|
||||
self.recordMicroseconds(value)
|
||||
case .milliseconds(let value):
|
||||
|
|
|
|||
|
|
@ -224,18 +224,22 @@ class MetricsTests: XCTestCase {
|
|||
// run the test
|
||||
let timer = Timer(label: "test-timer")
|
||||
let testTimer = timer.handler as! TestTimer
|
||||
// micro
|
||||
timer.recordMicroseconds(UInt64.max)
|
||||
// nano
|
||||
timer.recordNanoseconds(UInt64.max)
|
||||
XCTAssertEqual(testTimer.values.count, 1, "expected number of entries to match")
|
||||
XCTAssertEqual(testTimer.values[0].1, Int64.max, "expected value to match")
|
||||
// milli
|
||||
timer.recordMilliseconds(UInt64.max)
|
||||
// micro
|
||||
timer.recordMicroseconds(UInt64.max)
|
||||
XCTAssertEqual(testTimer.values.count, 2, "expected number of entries to match")
|
||||
XCTAssertEqual(testTimer.values[1].1, Int64.max, "expected value to match")
|
||||
// seconds
|
||||
timer.recordSeconds(UInt64.max)
|
||||
// milli
|
||||
timer.recordMilliseconds(UInt64.max)
|
||||
XCTAssertEqual(testTimer.values.count, 3, "expected number of entries to match")
|
||||
XCTAssertEqual(testTimer.values[2].1, Int64.max, "expected value to match")
|
||||
// seconds
|
||||
timer.recordSeconds(UInt64.max)
|
||||
XCTAssertEqual(testTimer.values.count, 4, "expected number of entries to match")
|
||||
XCTAssertEqual(testTimer.values[3].1, Int64.max, "expected value to match")
|
||||
}
|
||||
|
||||
func testGauge() throws {
|
||||
|
|
|
|||
Loading…
Reference in New Issue