Skip to content

Commit

Permalink
Add Swift using SIMD
Browse files Browse the repository at this point in the history
  • Loading branch information
MacAndor committed Apr 9, 2023
1 parent fbe7267 commit d6412f0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Earthfile
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ collect-data:
BUILD +sbcl
BUILD +scala
BUILD +swift
BUILD +swift-simd
BUILD +zig

all:
Expand Down Expand Up @@ -388,6 +389,13 @@ swift:
RUN --no-cache swiftc leibniz.swift -O -o leibniz -clang-target native -lto=llvm-full
DO +BENCH --name="swift" --lang="Swift" --version="swift --version" --cmd="./leibniz"

swift-simd:
FROM swift:5.7-jammy
DO +PREPARE_DEBIAN
DO +ADD_FILES --src="leibniz-simd.swift"
RUN --no-cache swiftc leibniz-simd.swift -O -o leibniz -clang-target native -lto=llvm-full
DO +BENCH --name="swift" --lang="Swift" --version="swift --version" --cmd="./leibniz"

zig:
# On 3.16 there is no zig package, but on edge there is
FROM alpine:edge
Expand Down
28 changes: 28 additions & 0 deletions src/leibniz-simd.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import Foundation

let text = try! String(contentsOfFile: "rounds.txt").split(separator: "\n")[0]
var rounds = UInt(text)!

var pi: Double = 1.0

let roundsRemainder = rounds % 4
rounds -= roundsRemainder

rounds += 2 // do this outside the loop

var i: UInt = 2
while i < rounds {
let xVec = SIMD4<Double>(-1.0, 1.0, -1.0, 1.0)
let iVec = SIMD4<Double>(Double(i) + 0, Double(i) + 1, Double(i) + 2, Double(i) + 3)
pi += (xVec / (2.0 * iVec - 1.0)).sum()
i += 4
}

for _ in 0..<roundsRemainder {
let x = -1.0 + 2.0 * Double(i & 1)
pi += x / Double(2 * i - 1)
i += 1
}

pi *= 4.0
print(String(format: "%.16f", pi))

0 comments on commit d6412f0

Please sign in to comment.