Code Measure Kit is a Swift package that provides an easy way to measure the execution rate of code blocks or functions. It is particularly useful for performance monitoring and tracking how frequently specific parts of your code are executed over time.
- Track the call rate of functions and code blocks.
- Aggregate metrics, including minimum, maximum, and total call counts.
- Thread-safe.
- Lightweight, with support for periodic updates.
- Simple integration with existing Swift code.
Add Code Measure Kit to your Package.swift dependencies:
dependencies: [
.package(url: "https://github.com/ipavlidakis/code-measure-kit.git", from: "0.1.2")
]To start measuring how often a function is called, you can use the measureCallRate function. Here's an example:
import CodeMeasureKit
func someFunction() {
measureCallRate()
// Function logic here
}In the example above, measureCallRate() will track how often someFunction() is called and automatically log the results every second.
You can also measure how long it takes for a block of code (synchronous or asynchronous) to execute using measureExecutionTime.
import CodeMeasureKit
func performSomeTask() {
let result = measureExecutionTime {
// Code whose execution time is being measured
performComputation()
}
print("Result: \(result)")
}In this example, the execution time of performComputation() will be measured, and the result will be printed once it completes. If isEnabled is false, the execution time will not be logged.
import CodeMeasureKit
func performSomeAsyncTask() async {
let result = await measureExecutionTime {
// Asynchronous code whose execution time is being measured
await performAsyncComputation()
}
print("Result: \(result)")
}In this asynchronous example, the execution time of performAsyncComputation() will be measured. The result will be printed once the asynchronous task completes. If isEnabled is false, the execution time will not be logged.
The measurement can be globally enabled or disabled using the isEnabled flag:
isEnabled = false // Disable performance measurement
isEnabled = true // Enable performance measurementThis package is available under the MIT License. See the LICENSE file for more details.