Created
April 8, 2024 07:49
-
-
Save kibotu/b6c6e0e97a00473cca913143150481f8 to your computer and use it in GitHub Desktop.
testing iOS concurrency speed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
Author
kibotu
commented
Apr 8, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment