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

Re: [pygame] [Pygame] How can I have an accurate timing when I am showing an image?



That's actually a standard problem with scheduling; you'll sometimes
be jostled out of the delay before the time is up.  The solution that
the sched module uses is essentially this:

startTime = time.time()
desiredEndTime = startTime + TIME_TEST_IMAGE
# Your setup would go here.
while True:
    current_time = time.time()
    if current_time >= desiredEndTime:
        break
    else:
        pygame.time.delay(desiredEndTime - time.time())

For a delay of 800 ms, you might want to use pygame.time.wait.  If
that's not accurate enough (I'm only seeing ~1ms off), you can always
use pygame.time.wait for the first 700 ms, and then use that loop for
the last 100 ms.

Also, if the exact display time is critical, you might want to take a
look into how long it takes to display and clear the image, move as
much of that work as possible elsewhere, and adjust your timing for
what you can't avoid.  Loading and blitting the image, for instance,
could be moved before the start, since the image isn't actually
displayed until you call display.update.

-Charlie Nolan

On Fri, May 23, 2008 at 2:38 PM, Francesco Martino
<francesco.k@xxxxxxxxx> wrote:
> I am using Pygame for building a psychological experiment.
> The code should do something very easy: it should display an image for
> a limited amount of time, then show a blank screen and then another
> image. Images are stored as bitmap files (470 Kb each).
> The main requisite for this program is that timing needs to be very
> accurate, namely if I say that an image should be displayed for 800
> msec the amount of error should be as little as possibile.
>
> The code is very simple: each image is shown using
>
>        startTime = time.time()
>        test = image.load(image1).convert() #image1 is the name of the file
>        surf.blit(test, (0,0))
>        display.update()
>        pygame.time.delay(TIME_TEST_IMAGE)
>        stopTime = time.time()
>        img_length = stopTime - startTime
>
> Using the Python time module, I see that error is acceptable for my
> purposes (the range is TIME_TEST_image +/-1, plus a costant error of
> 45 msec, so image is displayed for about 845 msec) in most of the
> cases. Unfortunately, sometimes the image is displayed for a shorter
> time (with a costant error of 11 msec, so image is displayed for about
> 811 msec) Since it happens with an irregular rate, it is very
> difficult to understand the reason. Has anyone some ideas? Is there a
> better way to display images for a fixed period of time with pygame?
>
> Thank you for any idea
> Francesco
>