pygame.time

Control the frame rate with Clock, measure elapsed time with get_ticks(), and schedule repeating or one-off events with set_timer().

2 min readUpdated
On this page

Overview#

pygame.time measures time in milliseconds. Its Clock class limits the frame rate and reports how long each frame took, which is the basis of smooth, frame-rate independent movement.

Syntax#

Python
clock = pygame.time.Clock()
dt_ms = clock.tick(60)                       # limit to 60 FPS, return ms since last call
now = pygame.time.get_ticks()                # ms since pygame.init()
pygame.time.set_timer(event, millis, loops=0)
pygame.time.wait(milliseconds)
pygame.time.delay(milliseconds)

Clock methods#

MethodReturns / does
tick(framerate=0)Waits so the loop runs at most framerate times per second; returns the milliseconds since the previous call. Call once per frame.
tick_busy_loop(framerate=0)Like tick but spins the CPU for more precise timing.
get_time()Milliseconds used by the previous tick.
get_rawtime()Like get_time but excluding the waiting.
get_fps()Average frame rate over the last few frames.

Module functions#

FunctionMeaning
get_ticks()Milliseconds since pygame.init(). Use for timers and cooldowns.
set_timer(event, millis, loops=0)Posts event (a type or an Event) every millis ms. loops=1 fires once; 0 repeats forever. millis=0 stops the timer.
wait(ms)Sleeps, letting other programs use the CPU. Less precise.
delay(ms)Waits precisely using the CPU.

Don't use wait, delay or time.sleep to "pause" a game: the window stops processing events. Keep the loop running and skip updates instead.

Practical example#

time_example.pyDownload
"""pygame.time: Clock, tick() and delta time, get_ticks() timers and set_timer() events."""
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 300))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 28)

BLINK = pygame.event.custom_type()
pygame.time.set_timer(BLINK, 500)               # every 500 ms
pygame.time.set_timer(pygame.event.Event(pygame.USEREVENT, kind="once"), 2000, loops=1)  # once after 2 s

visible = True
start = pygame.time.get_ticks()                 # milliseconds since pygame.init()
cooldown_until = 0
message = ""

running = True
while running:
    dt = clock.tick(60) / 1000                  # seconds since the previous frame
    now = pygame.time.get_ticks()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == BLINK:
            visible = not visible
        elif event.type == pygame.USEREVENT and getattr(event, "kind", "") == "once":
            message = "2-second one-shot timer fired"
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and now >= cooldown_until:
            cooldown_until = now + 1500         # ability usable again in 1.5 s
            message = "Ability used!"

    screen.fill((20, 26, 46))
    elapsed = (now - start) / 1000
    screen.blit(font.render(f"Elapsed {elapsed:.1f}s   dt {dt * 1000:.1f} ms   FPS {clock.get_fps():.0f}", True, "white"), (20, 20))
    ready = max(0, cooldown_until - now) / 1000
    screen.blit(font.render("Space: ability " + ("ready" if ready == 0 else f"in {ready:.1f}s"), True, "gold"), (20, 60))
    screen.blit(font.render(message, True, "lightblue"), (20, 100))
    if visible:
        pygame.draw.circle(screen, "tomato", (600, 40), 12)
    pygame.display.flip()

pygame.quit()

It shows a blinking indicator driven by a repeating timer, a one-shot timer event and an ability cooldown measured with get_ticks().

Common errors#

  • Game runs at different speeds on different PCs: movement isn't multiplied by dt. See the game loop.
  • tick() called twice per frame halves your frame rate.
  • Timers keep firing after a game over: stop them with set_timer(event, 0).
  • Using time.time() for frame timing works, but mixing it with get_ticks() invites unit mix-ups (seconds versus milliseconds).

Version notes#

The loops argument of set_timer and passing an Event object were added in Pygame 2.0.1 and are available in both pygame and pygame-ce. pygame-ce also exposes pygame.Clock as a shortcut for pygame.time.Clock.

Official documentation#

↑ ↓ to moveEnter to openEsc to close