#define ITERATIONS (1024*1024*32)
int main(int argc, const char * argv[]) {
double then,now;
unsigned int i;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
OSSpinLock spinLock = OS_SPINLOCK_INIT;
@autoreleasepool {
NSLock *lock = [NSLock new];
then = CFAbsoluteTimeGetCurrent();
for (i = 0; i < ITERATIONS; i ++) {
[lock lock];
[lock unlock];
}
now = CFAbsoluteTimeGetCurrent();
NSLog(@"NSLock time is %f sec",now - then);
then = CFAbsoluteTimeGetCurrent();
for (i = 0; i < ITERATIONS; i ++) {
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
now = CFAbsoluteTimeGetCurrent();
NSLog(@"pthread_mutex time is %f sec",now - then);
then = CFAbsoluteTimeGetCurrent();
for (i = 0; i < ITERATIONS; i ++) {
OSSpinLockLock(&spinLock);
OSSpinLockUnlock(&spinLock);
}
now = CFAbsoluteTimeGetCurrent();
NSLog(@"OSSpinLock time is %f sec",now - then);
id obj = [NSObject new];
then = CFAbsoluteTimeGetCurrent();
for (i = 0; i < ITERATIONS; i ++) {
@synchronized(obj)
{
}
}
now = CFAbsoluteTimeGetCurrent();
NSLog(@"@synchronized time is %f sec",now - then);
}
return 0;
}
得到的结果如下: