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

Re: [pygame] pygame.time.get_ticks() vs. time.clock()



I don't think you can rely on the time to be accurate - especially
across machines, and different CPUs/OS's.

Inaccurate to within 10ms is what XP can do.

So... what to do?  I think maybe use one of the machines as a master
clock?  Then sync to that?

So you could add the master clocks time to every packet... then adjust
for latency?

I think you'd need something like that if people get a pause in the
internet anyway?




On 5/24/07, Mike Wyatt <mikejohnwyatt@xxxxxxxxx> wrote:
I'm working on a synchronized RTS using pygame and Python's socket
library, and I've discovered that the values returned by
pygame.time.get_ticks() and the time module's clock() method are not
consistent.  My test results suggest that pygame.time.get_ticks() runs
slightly faster than time.clock().  In other words,
pygame.time.get_ticks() runs faster than real time, assuming that
time.clock() is 100% accurate.

The difference is pretty small, but it is enough to cause a networked
game to go out of sync within a few seconds.  My desktop machine
(Athlon XP+ 2600, Windows XP sp2) seems more affected by this problem
than my laptop (Turion 64 1.6ghz), so they are executing time steps at
a slightly different rate, resulting in the stalling.

Both machines are running Windows XP service pack 2 with Python 2.4
and PyGame 1.7.1.

Here is some source code that will show this behavior:

-------------------------------------------------------------
import pygame, time

pygame.init()
pygame.display.set_mode( (100, 50) )
quit = False

while not quit:

        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        quit = True

        t = int(time.clock()*1000)
        p = pygame.time.get_ticks()

        print "%8s %8s (%8s)" % (p, t, t-p)

        time.sleep(1)
-------------------------------------------------------------

Output on desktop:
    1155        0 (   -1155)
    2156      993 (   -1163)
    3156     1988 (   -1168)
    4160     2987 (   -1173)
    5161     3983 (   -1178)
    6162     4979 (   -1183)
    7164     5974 (   -1190)
    8164     6971 (   -1193)
    9165     7971 (   -1194)
   10170     8968 (   -1202)
   11173     9965 (   -1208)
   12173    10960 (   -1213)
   13173    11955 (   -1218)
   14173    12952 (   -1221)
   15173    13944 (   -1229)

As you can see, the difference between the pygame.time.get_ticks() and
time.clock() is slowly increasing.  The difference is less pronounced
on my laptop, though.  The values grow apart by only 1 or 2
milliseconds per second.

Does anyone else see this behavior?  I think a quick fix would be to
use time.clock(), but I'd like to hear what other people recommend.