-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add benchmark testing to swift workflow
This update restructures the testing process in the swift workflow by enabling code coverage during testing. Additionally, a new benchmarking step has been added. A new benchmarking script, Benchmark.swift, has also been created to specify and run the benchmarks.
- Loading branch information
1 parent
dc73c3d
commit 6f2bb8d
Showing
2 changed files
with
59 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import Foundation | ||
|
||
public struct Benchmark { | ||
let name: String | ||
let operation: () -> Void | ||
let iterations: Int | ||
|
||
public init(name: String, iterations: Int = 1000, operation: @escaping () -> Void) { | ||
self.name = name | ||
self.iterations = iterations | ||
self.operation = operation | ||
} | ||
|
||
public func run() -> (name: String, averageTime: Double) { | ||
var totalTime: Double = 0 | ||
|
||
for _ in 1...iterations { | ||
let start = DispatchTime.now() | ||
operation() | ||
let end = DispatchTime.now() | ||
|
||
let nanoTime = Double(end.uptimeNanoseconds - start.uptimeNanoseconds) | ||
totalTime += nanoTime / 1_000_000_000 // Convert to seconds | ||
} | ||
|
||
let averageTime = totalTime / Double(iterations) | ||
return (name, averageTime) | ||
} | ||
} | ||
|
||
public func runBenchmarks(_ benchmarks: [Benchmark]) { | ||
print("Running \(benchmarks.count) benchmarks...") | ||
print("-----------------------------") | ||
|
||
for benchmark in benchmarks { | ||
let result = benchmark.run() | ||
print("\(result.name): \(result.averageTime) seconds (average over \(benchmark.iterations) iterations)") | ||
} | ||
} | ||
|
||
// Example usage: | ||
let benchmarks = [ | ||
Benchmark(name: "Array Sorting") { | ||
var arr = (1...1000).map { _ in Int.random(in: 1...1000) } | ||
arr.sort() | ||
}, | ||
Benchmark(name: "String Concatenation", iterations: 10000) { | ||
var str = "" | ||
for _ in 1...100 { | ||
str += "Hello, World! " | ||
} | ||
} | ||
] | ||
|
||
runBenchmarks(benchmarks) |