I'm playing with the GLGravity example to figure out some of the performance nuances related to dealing with the accelerometer.
Here's the problem code:
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
static int accelCallCount;
accelCallCount++;
if (accelCallCount % 100 == 0) {
NSLog(@"accelCallCount:%d", accelCallCount);
}
//Use a basic low-pass filter to only keep the gravity in the accelerometer values
accel[0] = acceleration.x * kFilteringFactor + accel[0] * (1.0 - kFilteringFactor);
accel[1] = acceleration.y * kFilteringFactor + accel[1] * (1.0 - kFilteringFactor);
accel[2] = acceleration.z * kFilteringFactor + accel[2] * (1.0 - kFilteringFactor);
//Update the accelerometer values for the view
[glView setAccel:accel];
}
This code runs very slowly. Visually, I can tell that the movement of the teapot becomes very delayed, and it just gets slower and slower. Eventually the teapot's movements are easily 2+ minutes delayed from the time I actually moved the device.
The output in the Debugger Console does show some delay, too, but it's not too much. It's nearly (but not quite) twice as slow as it should be.
2009-11-27 02:18:58.874 GLGravity[419:207] accelCallCount:100
2009-11-27 02:19:00.507 GLGravity[419:207] accelCallCount:200
2009-11-27 02:19:02.174 GLGravity[419:207] accelCallCount:300
Accelerometer callbacks seem to pile up, though, in some kind of queue. So what starts off as being not-too-bad quickly becomes unbearably slow.
This problem disappears, however, if I just move the declaration of accelCallCount to the header file and declare it as an instance var:
int accelCallCount;
Why does this fix it?
On a related note, whether I use this code or the "fixed" (accelCallCount as an ivar) code, the whole thing also slows down if I touch the screen. Why might that be?