[OLPC-Games] Reducing pygame cpu-load to < 4 %

Chris Hager chris at linuxuser.at
Sun Dec 9 19:28:49 EST 2007


Chris Ball wrote:
>    > We figured out, a combination of pygame.event.wait() and
>    > pygame.event.get() very good. That's the demo code; it takes less
>    > than 4% cpu (0.3% - 1.7% here):
>
> That's cool.  Note that this won't work for any pygame activity that
> wants to do something in the background, though,
Not neccesarily; threads can help out here.
- The point is not to enter an ininite loop with pygame.event.get() (99%)
- a threaded infinite-loop consumes just ~ 20% cpu
- the same loop paused with time.sleep(0.1) brings it down to 1.4%
- and you can still react to all pygame events

I'd think about something like this:

import sys
import pygame
from pygame.locals import *

import time
import threading

class MyThread (threading.Thread):
    def run(self):
        while True:
            print 'Do your stuff or whatever : )'
            time.sleep(.1)

def main():
    window = pygame.display.set_mode((400, 225))
    pygame.event.set_blocked(MOUSEMOTION)
    pygame.init()

    MyThread().start()

    while True:
        for event in [ pygame.event.wait() ] + pygame.event.get( ):
            print event
            if event.type == KEYUP:
                # Quit on 'q'
                if event.key == 113: sys.exit(0)

if __name__=="__main__":
    main()


- chris


More information about the Games mailing list