我正在寻找加快冗长计算的方法(使用两个嵌套的 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);
有没有办法让这个执行更快?