Skip to content

Instantly share code, notes, and snippets.

@kibotu
Created April 8, 2024 07:49
Show Gist options
  • Save kibotu/b6c6e0e97a00473cca913143150481f8 to your computer and use it in GitHub Desktop.
Save kibotu/b6c6e0e97a00473cca913143150481f8 to your computer and use it in GitHub Desktop.
testing iOS concurrency speed
import Foundation
class Queue {
private var counter = 0.0
private let queue = DispatchQueue(label: "counter")
func increment() {
queue.sync {
counter += 1.2
}
}
}
class Lock {
private var lock = NSLock()
private var counter = 0.0
func increment() {
lock.lock()
counter += 1.2
lock.unlock()
}
}
class UnfairLock {
private var lock = os_unfair_lock_s()
private var counter = 0.0
func increment() {
os_unfair_lock_lock(&lock)
counter += 1.2
os_unfair_lock_unlock(&lock)
}
}
actor ActorCounter {
private var counter = 0.0
func increment() {
counter += 1.2
}
}
let clock = ContinuousClock()
/// Queue
let queue = Queue()
Task {
var startTime = clock.now
for _ in 0...10000 {
queue.increment()
}
print("Queue duration: \(clock.now - startTime) ms")
}
/// MARK unfair lock
let lock = Lock()
Task {
var startTime = clock.now
for _ in 0...10000 {
lock.increment()
}
print("Lock duration: \(clock.now - startTime) ms")
}
let unfairLock = UnfairLock()
Task {
var startTime = clock.now
for _ in 0...10000 {
unfairLock.increment()
}
print("Unfair lock duration: \(clock.now - startTime) ms")
}
/// Actor
let actor = ActorCounter()
Task {
var startTime = clock.now
for _ in 0...10000 {
await actor.increment()
}
print("Actor duration: \(clock.now - startTime) ms")
}
@kibotu
Copy link
Author

kibotu commented Apr 8, 2024

Queue duration: 2.293191709 seconds ms
Lock duration: 1.99675525 seconds ms
Unfair lock duration: 1.31649225 seconds ms
Actor duration: 0.009787958 seconds ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment