• 互斥锁、自旋锁、dispatch_once性能对比


    代码:

    #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
  • 相关阅读:
    中国移动神州行5元卡普遍缺货
    中国移动:抢占4G开展先机 上马手机付出
    广东可团购烧号CDMA版iPhone 4
    买了一款新手机!show 一下
    提供浙江大学信息与通信工程专业的考研资料
    实习实习!
    考研or保研?
    处理 NSOpertion 间依赖关系的一种方式
    2D & 3D Engine Resource
    在 iOS 应用中使用 Lua 作为模块粘合剂的方法
  • 原文地址:https://www.cnblogs.com/xwoder/p/4734575.html
Copyright © 2020-2023  润新知