我正在寻找加速冗长计算的方法(使用两个嵌套的 for 循环),其结果将显示在图中。我尝试了 NSOperationQueue ,认为每个内部 for 循环都会同时运行。但显然情况并非如此,至少在我的实现中是这样。如果我删除 NSOperationQueue 调用,我会在图中得到结果,因此我知道计算已正确完成。
这是一个代码片段:
NSInteger half_window, len;
len = [myArray length];
if (!len)
return;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
half_window = 0.5 * (self.slidingWindowSize - 1);
numberOfPoints = len - 2 * half_window;
double __block minY = 0;
double __block maxY = 0;
double __block sum, y;
xPoints = (double *) malloc (numberOfPoints * sizeof(double));
yPoints = (double *) malloc (numberOfPoints * sizeof(double));
for ( NSUInteger i = half_window; i < (len - half_window); i++ )
{
[queue addOperationWithBlock: ^{
sum = 0.0;
for ( NSInteger j = -half_window; j <= half_window; j++ )
{
MyObject *mo = [myArray objectAtIndex: (i+j)];
sum += mo.floatValue;
}
xPoints[i - half_window] = (double) i+1;
y = (double) (sum / self.slidingWindowSize);
yPoints[i - half_window] = y;
if (y > maxY)
maxY = y;
if (y < minY)
minY = y;
}];
[queue waitUntilAllOperationsAreFinished];
}
// update my core-plot
self.maximumValueForXAxis = len;
self.minimumValueForYAxis = floor(minY);
self.maximumValueForYAxis = ceil(maxY);
[self setUpPlotSpaceAndAxes];
[graph reloadData];
// cleanup
free(xPoints);
free(yPoints);
有没有办法让它执行得更快?
最佳答案
添加每个项目后,您正在等待队列中的所有操作完成。
[queue waitUntilAllOperationsAreFinished];
}
// update my core-plot
self.maximumValueForXAxis = len;
应该是
}
[queue waitUntilAllOperationsAreFinished];
// update my core-plot
self.maximumValueForXAxis = len;
您还将每个操作队列 block 中的 sum
变量设置为 0.0。
关于ios - 使用 NSOperationQueue 加速长计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16408324/