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

[pygame] A new pygame.time.Clock?



I have made a pure python version of pygame.time.Clock that currently just supports the tick method but I think I could expand it to have all the same functionality of the current class but without using a busy loop. Here is a test I did as well over 4 minutes the python version (frmrate) was quite a bit more accurate as well although that maybe due to the pygame clock being more susceptible to losing time because of other processes. If you want to put it into pygame I'll add the rest of the methods.

>>> t = timeit.Timer('c.tick(50)', 'import frmrate; c = frmrate.Clock()')
>>> t.timeit(12000)
240.12974309921265
>>> t = timeit.Timer('c.tick(50)', 'import pygame; c = pygame.time.Clock ()')
>>> t.timeit(12000)
245.36062693595886

Here's the code so far:

import time

class Clock:
    def __init__(self):
        self.t = time.time()
       
    def tick(self, rate):
        self.rate = rate
# This is used to make the return values the same as in the C version.
        retVal = int(round((time.time() - self.t) * 1000, 0))
        self.stop()
        self.t = time.time ()
        return retVal
           
    def stop(self):
        frmlen = 1.0/self.rate
        try:
            time.sleep(frmlen - (time.time() - self.t))
        except IOError:
# Catches exceptions raised by time.sleep because your computer is too slow!
# ie you passed it a negative number
            pass
       
if __name__ == "__main__":
# This is a testing section that can be removed.
    import timeit
    timer = timeit.Timer('c.tick(50)', 'import frmrate; c = frmrate.Clock()')
    print timer.timeit(12000)