Sure, I will post a few snippets. These are all on an M1 Pro.
Creating an array of data for later passing in to the Metal buffer:
let arrayLength = (1 << 24)
let randomRange: ClosedRange<Float> = 0...Float(100.0)
var randomFloats: [Float] = []
randomFloats.reserveCapacity(arrayLength)
print("Capacity reserved")
let start = DispatchTime.now()
for _ in 0..<arrayLength {
randomFloats.append(Float.random(in: randomRange))
}
let end = DispatchTime.now()
let totalTime = Double(end.uptimeNanoseconds - start.uptimeNanoseconds) / 1_000_000_000.0
print("Total time \(totalTime) seconds.")
The output for this one is:
Capacity reserved
Total time 11.37157275 seconds.
Program ended with exit code: 0
Here we try to create the Metal buffer directly:
guard let device = MTLCreateSystemDefaultDevice() else {
fatalError( "Failed to get the system's default Metal device." )
}
let arrayLength = (1 << 24)
let bufferSize = arrayLength * MemoryLayout<Float>.size
let randomRange: ClosedRange<Float> = 0...Float(100.0)
print("Starting")
let start = DispatchTime.now()
guard let buffer = device.makeBuffer(bytes: (0..<arrayLength).map { _ in Float.random(in: randomRange) },
length: bufferSize,
options: .storageModeShared) else {
fatalError( "Failed to make buffer" )
}
let end = DispatchTime.now()
let totalTime = Double(end.uptimeNanoseconds - start.uptimeNanoseconds) / 1_000_000_000.0
print("Total time \(totalTime) seconds.")
The output for this one is:
2022-09-03 08:43:27.183968-0500 computeTest[2988:125455] Metal GPU Frame Capture Enabled
2022-09-03 08:43:27.184253-0500 computeTest[2988:125455] Metal API Validation Enabled
Starting
Total time 10.732446667 seconds.
Program ended with exit code: 0
I've tried a number of others, but this should give a good idea of what is going on. Using GKLinearCongruentialRandomSource from GameKit speeds it up by a few percent, but it still doesn't compare to the Objective-C version in the above linked sample code. That entire program runs in less than 1 second on my MacBook Pro.