Created
February 25, 2017 19:26
-
-
Save andersio/215d3f469e8c428b0b00bcf9706f8e52 to your computer and use it in GitHub Desktop.
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
let info = mach_timebase_info_t.allocate(capacity: 1) | |
mach_timebase_info(info) | |
var avg: Double = 0 | |
let lock: UnsafeMutableRawPointer! | |
if #available(macOS 10.12, iOS 10.0, *), true { | |
let lock1 = os_unfair_lock_t.allocate(capacity: 1) | |
lock1.initialize(to: os_unfair_lock()) | |
lock = UnsafeMutableRawPointer(lock1) | |
} else { | |
lock = nil | |
} | |
for _ in 0 ..< 1000000 { | |
let s = mach_absolute_time() | |
if #available(macOS 10.12, *) { | |
os_unfair_lock_lock(lock.assumingMemoryBound(to: os_unfair_lock_s.self)) | |
os_unfair_lock_unlock(lock.assumingMemoryBound(to: os_unfair_lock_s.self)) | |
} | |
let e = mach_absolute_time() | |
avg += Double((e - s) * UInt64(info.pointee.numer) / UInt64(info.pointee.denom)) / 1000000 | |
} | |
print("avg: \(avg) ns") | |
if #available(macOS 10.12, *) { | |
var avg2: Double = 0 | |
let lk = lock.assumingMemoryBound(to: os_unfair_lock_s.self) | |
for _ in 0 ..< 1000000 { | |
let s = mach_absolute_time() | |
os_unfair_lock_lock(lk) | |
os_unfair_lock_unlock(lk) | |
let e = mach_absolute_time() | |
avg2 += Double((e - s) * UInt64(info.pointee.numer) / UInt64(info.pointee.denom)) / 1000000 | |
} | |
print("avg: \(avg2) ns (no #available)") | |
} | |
let lock3 = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1) | |
lock3.initialize(to: pthread_mutex_t()) | |
pthread_mutex_init(lock3, nil) | |
var avg3: Double = 0 | |
for _ in 0 ..< 1000000 { | |
let s = mach_absolute_time() | |
pthread_mutex_lock(lock3) | |
pthread_mutex_unlock(lock3) | |
let e = mach_absolute_time() | |
avg3 += Double((e - s) * UInt64(info.pointee.numer) / UInt64(info.pointee.denom)) / 1000000 | |
} | |
print("avg: \(avg3) ns (pthread)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment