> ## Content Index
> Fetch the complete content index at: https://developerinsider.co/llms.txt
> Use this file to discover other available public pages before exploring further.

# How to measure function execution time in Swift?
- URL: https://developerinsider.co/how-to-measure-function-execution-time-in-swift/
- Published: 2023-09-26T06:00:33.000Z
- Updated: 2023-10-17T04:52:44.000Z
- Author: Vineet Choudhary
- Tags: Swift, ContinuousClock

Runtime code execution duration monitoring is crucial. Swift provides `ContinuousClock` to measures the time that always increments. The `ContinuousClock` acts like a stopwatch, measuring time relative to when a program starts or some other specific reference point. This is suitable for high resolution measurements of execution.

## 1\. Measure function execution time

You can use `ContinuousClock` `measure(_:)` function to measure execution time for any function/code. You can use the `measure(_:)` function like this:

```swift
let clock = ContinuousClock()
let elapsed = clock.measure {
    someWork()
}
print("Time: \(elapsed)")

```

## 2\. Measure asynchronous function execution time

If you want to measure an asynchronous function then you can use the asynchronous `measure(_:)` function like this:

```swift
let clock = ContinuousClock()
let elapsed = await clock.measure {
    await someWork()
}
print("Time: \(elapsed)")

```

## 3\. Example

For example, let's calculate the value of PI up to 4 decimal places using the Leibniz formula.

```swift
import Foundation

func calculatePI() {
	var gregoryLeibniz : Double = 0
	var counter = 1
	while (gregoryLeibniz * 4).round() != 3.1415 {
		var oddNumber = 2 * counter - 1
		if counter % 2 == 0 {
			gregoryLeibniz -= 1/Double(oddNumber)
		}
		else {
			gregoryLeibniz += 1/Double(oddNumber)
		}
		print((gregoryLeibniz * 4).round())
		counter += 1
	}
}

extension Double {
	func round() -> Double {
		let divisor = pow(10.0, Double(4))
		return (self * divisor).rounded() / divisor
	}
}

let clock = ContinuousClock()
let elapsed = clock.measure {
	calculatePI()
}

print("Time took to calculate pi upto 4 place \(elapsed)")

```

In the above example, inside the `calculatePI()` function there is a `print` statement. You can try to execute the same code with and without `print` statement to measure the impact of adding `print` statement in our code.

#### With print statement

![](https://cdn.developerinsider.co/images/ios/swift/clock/measure-with-print.webp)

#### Without print statement

![](https://cdn.developerinsider.co/images/ios/swift/clock/measure-without-print.webp)