Skip to content

Instantly share code, notes, and snippets.

@ncreated
Last active November 4, 2022 21:29

Revisions

  1. ncreated revised this gist Nov 4, 2022. 1 changed file with 5 additions and 4 deletions.
    9 changes: 5 additions & 4 deletions XCTestCase+Benchmark.swift
    Original file line number Diff line number Diff line change
    @@ -1,12 +1,13 @@
    extension XCTestCase {
    func benchmark(_ label: String, block: () -> Void) {
    func benchmark(_ label: String, iterations: Int = 100, block: () throws -> Void) rethrows {
    var measures: [TimeInterval] = []
    let warmUp = iterations / 10

    for i in (0..<1_010) {
    for i in (0..<iterations) {
    let start = Date()
    block()
    try block()

    if i >= 10 { // only measure after it is warmed-up
    if i >= warmUp { // only measure after it is warmed-up
    let stop = Date()
    measures.append(stop.timeIntervalSince(start))
    }
  2. ncreated created this gist Nov 4, 2022.
    20 changes: 20 additions & 0 deletions XCTestCase+Benchmark.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    extension XCTestCase {
    func benchmark(_ label: String, block: () -> Void) {
    var measures: [TimeInterval] = []

    for i in (0..<1_010) {
    let start = Date()
    block()

    if i >= 10 { // only measure after it is warmed-up
    let stop = Date()
    measures.append(stop.timeIntervalSince(start))
    }
    }

    let sum = measures.reduce(0, +)
    let avg = sum / Double(measures.count)

    print("⭐️ AVG in \(label): \(avg * 1_000) ms")
    }
    }