Skip to content

Instantly share code, notes, and snippets.

@tornikegomareli
Last active April 16, 2025 11:05
Show Gist options
  • Save tornikegomareli/05d523a642b4bee0415f70553b390362 to your computer and use it in GitHub Desktop.
Save tornikegomareli/05d523a642b4bee0415f70553b390362 to your computer and use it in GitHub Desktop.
import Foundation
let vectorSize = 10_000_000
print("Running Swift vector dot product benchmark with size: \(vectorSize)")
struct Vector3D {
let x: Double
let y: Double
let z: Double
func dot(_ other: Vector3D) -> Double {
return x * other.x + y * other.y + z * other.z
}
static func random() -> Vector3D {
return Vector3D(
x: Double.random(in: Double.leastNormalMagnitude...Double.greatestFiniteMagnitude)
* (Bool.random() ? 1 : -1),
y: Double.random(in: Double.leastNormalMagnitude...Double.greatestFiniteMagnitude)
* (Bool.random() ? 1 : -1),
z: Double.random(in: Double.leastNormalMagnitude...Double.greatestFiniteMagnitude)
* (Bool.random() ? 1 : -1)
)
}
}
print("Generating \(vectorSize) random 3D vectors...")
var vectorsA = [Vector3D]()
var vectorsB = [Vector3D]()
func calculateAllDotProducts(_ a: inout [Vector3D], _ b: inout [Vector3D]) -> Double {
var sum = 0.0
for i in 0..<vectorSize {
a.append(Vector3D.random())
b.append(Vector3D.random())
sum += a[i].dot(b[i])
}
return sum
}
print("Starting benchmark...")
let start = Date()
let result = calculateAllDotProducts(&vectorsA, &vectorsB)
let timeElapsed = Date().timeIntervalSince(start)
let minutes = Int(timeElapsed) / 60
let seconds = Int(timeElapsed) % 60
let milliseconds = Int((timeElapsed - Double(Int(timeElapsed))) * 1000)
print("Result: \(result)")
print("Time breakdown: \(minutes) minutes, \(seconds) seconds, \(milliseconds) milliseconds")
print("Total time in seconds: \(timeElapsed)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment