代码:
#import <Foundation/Foundation.h> #import <pthread.h> extern uint64_t dispatch_benchmark(size_t count, void (^block)(void)); // pthread_mutex_lock void dispatch_once_pthread(dispatch_once_t *, dispatch_block_t); // spinlock void dispatch_once_spinlock(dispatch_once_t *, dispatch_block_t); int main(int argc, const char * argv[]) { size_t count = 1000000; // pthread_mutex_lock uint64_t time1 = dispatch_benchmark(count, ^{ static dispatch_once_t onceToken; dispatch_once_pthread(&onceToken, ^{ }); }); NSLog(@"dispatch_once_pthread = %llu ns", time1); // spinlock uint64_t time2 = dispatch_benchmark(count, ^{ static dispatch_once_t onceToken; dispatch_once_spinlock(&onceToken, ^{ }); }); NSLog(@"dispatch_once_spinlock = %llu ns", time2); // dispatch_once uint64_t time3 = dispatch_benchmark(count, ^{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ }); }); NSLog(@"dispatch_once = %llu ns", time3); return 0; } // pthread_mutex_lock void dispatch_once_pthread(dispatch_once_t *predicate, dispatch_block_t block) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); if(!*predicate) { block(); *predicate = 1; } pthread_mutex_unlock(&mutex); } // spinlock void dispatch_once_spinlock(dispatch_once_t *predicate, dispatch_block_t block) { static OSSpinLock lock = OS_SPINLOCK_INIT; OSSpinLockLock(&lock); if(!*predicate) { block(); *predicate = 1; } OSSpinLockUnlock(&lock); }
输出:
dispatch_once_pthread = 57 ns dispatch_once_spinlock = 22 ns dispatch_once = 15 ns
时间: 2024-10-17 12:00:41