@@ -19,6 +19,7 @@ import XCTest
19
19
@testable import Metrics
20
20
21
21
class MetricsExtensionsTests : XCTestCase {
22
+ @available ( * , deprecated)
22
23
func testTimerBlock( ) throws {
23
24
// bootstrap with our test metrics
24
25
let metrics = TestMetrics ( )
@@ -220,6 +221,43 @@ class MetricsExtensionsTests: XCTestCase {
220
221
" expected value to match "
221
222
)
222
223
}
224
+
225
+ #if compiler(>=6.0)
226
+ func testTimerMeasure( ) async throws {
227
+ // bootstrap with our test metrics
228
+ let metrics = TestMetrics ( )
229
+ MetricsSystem . bootstrapInternal ( metrics)
230
+ // run the test
231
+ let name = " timer- \( UUID ( ) . uuidString) "
232
+ let delay = Duration . milliseconds ( 5 )
233
+ let timer = Timer ( label: name)
234
+ try await timer. measure {
235
+ try await Task . sleep ( for: delay)
236
+ }
237
+
238
+ let expectedTimer = try metrics. expectTimer ( name)
239
+ XCTAssertEqual ( 1 , expectedTimer. values. count, " expected number of entries to match " )
240
+ XCTAssertGreaterThan ( expectedTimer. values [ 0 ] , delay. nanosecondsClamped, " expected delay to match " )
241
+ }
242
+
243
+ @MainActor
244
+ func testTimerMeasureFromMainActor( ) async throws {
245
+ // bootstrap with our test metrics
246
+ let metrics = TestMetrics ( )
247
+ MetricsSystem . bootstrapInternal ( metrics)
248
+ // run the test
249
+ let name = " timer- \( UUID ( ) . uuidString) "
250
+ let delay = Duration . milliseconds ( 5 )
251
+ let timer = Timer ( label: name)
252
+ try await timer. measure {
253
+ try await Task . sleep ( for: delay)
254
+ }
255
+
256
+ let expectedTimer = try metrics. expectTimer ( name)
257
+ XCTAssertEqual ( 1 , expectedTimer. values. count, " expected number of entries to match " )
258
+ XCTAssertGreaterThan ( expectedTimer. values [ 0 ] , delay. nanosecondsClamped, " expected delay to match " )
259
+ }
260
+ #endif
223
261
}
224
262
225
263
// https://bugs.swift.org/browse/SR-6310
@@ -251,3 +289,25 @@ extension DispatchTimeInterval {
251
289
}
252
290
}
253
291
}
292
+
293
+ #if swift(>=5.7)
294
+ @available ( macOS 13 , iOS 16 , tvOS 16 , watchOS 9 , * )
295
+ extension Swift . Duration {
296
+ fileprivate var nanosecondsClamped : Int64 {
297
+ let components = self . components
298
+
299
+ let secondsComponentNanos = components. seconds. multipliedReportingOverflow ( by: 1_000_000_000 )
300
+ let attosCompononentNanos = components. attoseconds / 1_000_000_000
301
+ let combinedNanos = secondsComponentNanos. partialValue. addingReportingOverflow ( attosCompononentNanos)
302
+
303
+ guard
304
+ !secondsComponentNanos. overflow,
305
+ !combinedNanos. overflow
306
+ else {
307
+ return . max
308
+ }
309
+
310
+ return combinedNanos. partialValue
311
+ }
312
+ }
313
+ #endif
0 commit comments