【发布时间】:2023-03-31 21:30:02
【问题描述】:
我正在使用 Objective-C 处理图像并尝试了 Grand Central Dispatch,结果很糟糕。 CPU 使用率增加了一倍,处理图像的时间也增加了一倍。
- (void) processImage:(struct ImageData)image {
imageData = image;
[allyMinionManager prepareForPixelProcessing];
int cores = 4;
int section = imageData.imageHeight/cores;
if (section < 1) {
section = 1;
}
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < cores; i++) {
int yStart = section * i;
int yEnd = yStart + section;
if (i == cores - 1) {
yEnd = imageData.imageHeight;
}
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
for (int y = yStart; y < yEnd; y++) {
uint8_t *pixel = imageData.imageData + (y * imageData.imageWidth)*4;
for (int x = 0; x < imageData.imageWidth; x++) {
[allyMinionManager processPixel:pixel x:x y:y];
pixel += 4;
}
}
dispatch_group_leave(group);
});
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
[allyMinionManager postPixelProcessing:imageData];
}
我在核心之间分离图像,然后等待分派的任务完成。如果我有一个 1200x800 的图像,每个线程应该处理 240,000 像素。
Core 设置为 1:95% CPU 使用率,16ms 处理时间
Core 设置为 4:120% CPU 使用率,33ms 处理时间
知道为什么性能这么差吗?
(额外问题:当我将编译器优化标志设置为最低时,我的程序中的 CPU 使用率从 45% 变为 300%。这正常吗?)
【问题讨论】:
-
我切换到 dispatch_apply,似乎比我以前的方法好很多。虽然我的 CPU 使用率在 2 个内核时上升了 10%,但在 4 个或更多内核时上升了 50%。我没有测试处理速度,因为它发生得太快了,我的处理以恒定的 60fps 运行。我会让它保持多线程,以防我的处理变得过于密集并且 1 个核心运行速度低于 60fps。如果您将其粘贴为答案,我会将您的评论标记为答案。
标签: objective-c multithreading image-processing grand-central-dispatch