[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Pygame, clock.ticks() and 42



On Sat, 2005-09-03 at 21:50 +1000, Richard Jones wrote:
> During final testing, we noticed something very odd: setting the Clock.ticks() 
> value to 42 (or more) results in 100% CPU utilisation on my computer. 41 
> barely loads the system (ie. about 5-10% CPU). 42 is evil.

I can only take a guess at what is going on here. The SDL sleep
functions are not always accurate. On several platforms they can have a
minimum response of 10ms. This means if you call pygame.time.wait(2) you
could end up still waiting a full 10ms, even though you asked for 2.
There is also the pygame.time.delay(2) call, which accurately waits for
2ms, but does so with a "busy loop" which eats up the cpu.

The pygame.Clock object tries to balance between these two calls. If
there is plenty of time remaining, it goes with a few
pygame.time.sleep() calls to let a lot of clock go past. Once it gets
close to the desired wait time, it switches to pygame.time.delay().

I'm guessing the threshold between 41fps and 42fps is where the Clock
deems it is necessary to use only "accurate" timing. The fact that it is
the number 42 is entirely a coincidence with Douglas Adams references.

It's been a long time since I looked at this code. I am not sure if it
would be different platform to platform. The simple Clock objects was
actually a bit tricky to write. It is the whole reason I added the
separate pygame.time.wait() and pygame.time.delay() calls is because I
could not get accurate framerates above certain speeds. This solves the
problem timingwise, but the 100% cpu burn is not very nice either.

It's not too complicated inside. I'm sure there are actual good
algorithms to all this, but I'm still a bit naive in regards to
cross-platform accurate timing. It should be very easy to retool some of
the logic.