我正在尝试实现一个函数,该函数创建我的自定义高优先级串行队列,以便在dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
确保只在我使用一次调度模式时创建此队列。但我遇到了性能问题。我的功能慢了三倍。这是代码:
dispatch_queue_t dispatch_get_custom_serial_queue() {
static dispatch_once_t onceToken;
static dispatch_queue_t CustomSerialQueue = nil;
dispatch_once(&onceToken, ^{
CustomSerialQueue = dispatch_queue_create("custom.serial.queue", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(CustomSerialQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
});
return CustomSerialQueue;
}
以下是测试:
- (void)testQueueCreation
{
CFAbsoluteTime startTime;
NSLog(@"****************************");
startTime = CFAbsoluteTimeGetCurrent();
dispatch_queue_t queue = dispatch_get_custom_serial_queue();
for (int i = 0; i < 1000000; i ++) {
dispatch_sync(queue, ^{
//
});
}
NSLog(@"assign queue once:\t %f seconds", CFAbsoluteTimeGetCurrent() - startTime);
startTime = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < 1000000; i ++) {
dispatch_sync(dispatch_get_custom_serial_queue(), ^{
//
});
}
NSLog(@"get queue each time:\t %f seconds", CFAbsoluteTimeGetCurrent() - startTime);
startTime = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < 1000000; i ++) {
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//
});
}
NSLog(@"get global queue each time:\t %f seconds", CFAbsoluteTimeGetCurrent() - startTime);
NSLog(@"****************************");
}
这就是结果:
****************************
assign queue once: 0.035383 seconds
get queue each time: 0.112233 seconds
get global queue each time: 0.044906 seconds
****************************
我想念什么以及如何更快地完成此功能?
答案 0 :(得分:1)
dispatch_get_global_queue不使用dispatch_once。该函数只获取一个静态变量。
我认为dispatch_queue_t queue = dispatch_get_custom_serial_queue(); and dispatch_sync(queue,
对于这种情况是个好主意。
答案 1 :(得分:1)
如果您想让dispatch_get_custom_serial_queue
更快,请摆脱dispatch_once
。在调用main
或UIApplicationMain
之前在NSApplicationMain
中创建队列,以确保在以后需要时存在。