Skip to content

Commit

Permalink
Add benchmark testing to swift workflow
Browse files Browse the repository at this point in the history
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
arkavo-com committed Jul 1, 2024
1 parent dc73c3d commit 6f2bb8d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/swift.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ on:

jobs:
build:

runs-on: macos-latest

steps:
- uses: actions/checkout@v4
- uses: maxim-lobanov/setup-xcode@v1
with:
xcode-version: latest-stable
- name: Build
run: swift build -v
- name: Run tests
run: swift test -v
- name: Test
run: swift test --enable-code-coverage -v
- name: Benchmark
run: swift OpenTDFKitTests/Benchmark.swift
55 changes: 55 additions & 0 deletions OpenTDFKitTests/Benchmark.swift
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)

0 comments on commit 6f2bb8d

Please sign in to comment.