Home
Map
ContinuousClock ExampleUse the ContinuousClock to measure the elapsed time of a function. Specify the function in a closure.
Swift
This page was last reviewed on Jan 16, 2024.
ContinuousClock. This Swift 5.9 class is a stopwatch: it can measure the time required for a block of code to run. We can then print or compare the elapsed times.
With a closure, we specify a block of code that we want to time. The measure function then returns a Duration that we can write to the console.
Example. This program uses the ContinuousClock as a stopwatch, and it measures a function 2 times. It changes the number of iterations passed to the function.
Step 1 We create a new clock. On this instance of ContinuousClock, we can call methods like measure.
Step 2 Use call measure and use a closure argument. In the closure, we call the test() function and specify 10000 iterations.
Step 3 We call measure again, but this time we specify slightly different code within the closure—we use 20000 iterations.
Step 4 It is possible to compare the Duration returned by measure against another Duration.
func test(iterations: Int) { // Run some slow computations. let items = ["bird", "frog", "dog", "cat"] var sum = 0 for _ in 0...iterations { for item in items { sum += item.count } } if sum == 0 { print("Error") } } // Step 1: create a new clock. let clock = ContinuousClock() // Step 2: call measure with a closure, and specify the iterations. let elapsed = clock.measure { test(iterations: 10000) } print(elapsed) // Step 3: call measure with a closure, using even more iterations. let elapsed2 = clock.measure { test(iterations: 20000) } print(elapsed2) // Step 4: we can compare the elapsed time Durations. if elapsed < elapsed2 { print("First version was faster") }
0.0049672 seconds 0.0095812 seconds First version was faster
Benchmarking. One way to learn how to write highly-efficient Swift code is to perform many micro-benchmarks of code. With ContinuousClock, this can be done without any complicated arithmetic.
It would be possible to use ContinuousClock to measure runtime performance, and then write this information to a file for later analysis. This could help diagnose sporadic slowdowns.
File
Date
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 16, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.