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

Re: [pygame] Why does pygame get so high CPU usage?



----- Original Message -----
From: "Pete Shinners" <pete@shinners.org>
To: <pygame-users@seul.org>
Sent: Saturday, July 19, 2003 6:32 PM
Subject: Re: [pygame] Why does pygame get so high CPU usage?


> Psymaster wrote:
> > while 1:
> >     for event in pygame.event.get(QUIT):
> >         sys.exit()
> >     pygame.event.pump()
>
> this is the part of your program that is burning cpu. this will get
> the same cpu usage as something like
>
> while 1:
>      a = 5
>
> something like this will use 100% cpu in any programming language on
> any platform. the program will use every available resource to
> constantly run what is in the loop. the good news is pygame gives
you
> a few ways to scale back your program and use 0% of the cpu.
>
> the first and easiest is usually used by simple games or test
> programs. you simply call "pygame.time.wait(1)" somewhere in your
> mainloop. on all platforms, the wait() function 'releases' the
process
> control back to the os kernel. a wait value of 1 in your loop will
> drop the cpu down to about 2-5%. if you go all the way up to wait(5)
> the program will definitely be under 1%. the wait method is simple,
> but it doesn't get the cpu usage as low as it can go, and it doesn't
> work well for games where framerate is important.
>
> for programs that have no real animation there is a better way. this
> is similar to the method used inside all GUI libraries. the trick is
> that the program doesn't need to do anything until the user does
> something with it. there is another 'wait' function in the event
> module. "pygame.event.wait()". this will freeze your program until
> there is some sort of event from the user or window system. using
this
> method the program really will take 0% of the cpu, unless the user
is
> interacting with the program. note that the MOUSEMOTION event can
> happen very often when the user is moving the mouse. if you don't
care
> about the mouse movement you can block those messages and save even
> more cpu time. your mainloop would look like this using the
event.wait,
>
> pygame.event.set_blocked(MOUSEMOTION)
> while 1:
>      event = pygame.event.wait()
>      if event.type == QUIT:
>          sys.exit()
>
>
> the other method involves using the pygame.time.Clock objects to
help
> limit the program framerate. this would be more useful in larger
> games, but overkill for an image viewer.
>
> hmm, time to start a FAQ.
>
>


Okay, I used event.wait() and it works now! Thanks for the quick
replies to all of you guys!