Duck
Duck

Reputation: 35993

Cocos2D 2.0 increasing schedule precision

I have this line in one of my scenes:

[self schedule:@selector(storeValue:) interval:1.0/30.0];

storeValue is very basic and fast. It just stores the position of a layer on an NSMutableArray. I need this storeValue to be called in as much precise as possible timings, but after making some measurements, these are the intervals measured between each storeValue call:

interval 0 = 0
interval 1 = 0.049962
interval 2 = 0.033345
interval 3 = 0.033332
interval 4 = 0.049994
interval 5 = 0.050050
interval 6 = 0.049968
interval 7 = 0.033998
interval 8 = 0.049331
interval 9 = 0.050015
interval 10 = 0.049979
interval 11 = 0.049999
interval 12 = 0.033357
interval 13 = 0.033307
interval 14 = 0.049997
interval 15 = 0.033322
interval 16 = 0.050317
interval 17 = 0.049743
interval 18 = 0.049973
interval 19 = 0.033322
interval 20 = 0.050024
interval 21 = 0.049975
interval 22 = 0.049987
interval 23 = 0.033316
interval 24 = 0.050038
interval 25 = 0.050149
interval 26 = 0.049852
interval 27 = 0.049989
interval 28 = 0.050011

So, as you see, the method is called with a variety of intervals instead of always being 0.03333 (1 / 30).

I have tried to remove all code from storeValue to see how frequently storeValue is called and obtained the same irregular timings.

The big question is this: what should I do to improve schedule precision? Should I use NSTimer? GCD any other method of doing a scheduled task? Any suggestions?

thanks.

NOTE: I've discovered now that if I put interval = 0, storeValue will be called every frame, that means 1/60s and the precision is awesome. OK, I can make a logic to call storeValue half of the time but it would be nice to know why schedule is so imprecise and if there is a way to improve it.

Upvotes: 1

Views: 528

Answers (2)

brigadir
brigadir

Reputation: 6942

When you schedule something, the selector and timer frequency are passed to Cocos2d sharedScheduler. Then sharedDirector calls [[Scheduler sharedScheduler] tick: dt]; on each frame. If your timer passes its threshold the scheduler calls your selector.

So the frequency cannot be more precise than mainloop frequency (max 1/60, min - depending on actual scene complexity). Probably 1/30 passes threshold not exactly on each 2nd frame and thats why you have not precise values in log.

I can propose to call your selector on other thread via NSTimer without using Cocos2d scheduler.

Upvotes: 1

MechEthan
MechEthan

Reputation: 5703

iOS isn't a Real-time operating system and thus you can never be guaranteed that your scheduled callback/NSTimer/etc. will ever occur at precisely 1/30 of a second. This precision will always vary based on what else the OS is handling.

What you can do, however, is use the actual time passed between each callback to account for this lack of consistency.

Upvotes: 0

Related Questions