Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 41 ยท Window, Loop and Events

Clock and Time in Pygame

Master pygame.time - Clock.tick and get_fps, tick_busy_loop, get_ticks for cooldowns and countdowns, wait and delay, and when to use timers instead of sleeping.

Games are all about time: how long a frame takes, how many seconds are left on a countdown, how long until a weapon can fire again. Pygame's pygame.time module gives you a Clock object for frame pacing plus functions for reading and waiting on the clock. This lesson shows each tool and the patterns built on them.

The Clock object

Create one Clock before the loop and call tick() once per frame:

Python
clock = pygame.time.Clock()

while running:
    ...
    dt_ms = clock.tick(60)       # cap at 60 FPS, returns ms since the last tick

tick(framerate) computes how long the frame has taken so far and sleeps for the remaining time, so the loop lasts about 1000 / framerate milliseconds. If your work already takes longer than that, it does not sleep and the frame rate simply falls below the target.

Method Returns
clock.tick(fps) Milliseconds since the previous tick call; delays to hold the cap
clock.tick_busy_loop(fps) Same, but more accurate because it spins instead of sleeping (uses more CPU)
clock.get_time() Milliseconds between the previous two tick calls
clock.get_rawtime() Like get_time() but without the time spent sleeping, i.e. the real work time
clock.get_fps() Average frame rate over the last ten ticks

Note: tick() is accurate to roughly a few milliseconds because it relies on the operating system's sleep. Use tick_busy_loop() only when you truly need precision, because it keeps the CPU busy.

Showing the FPS

A frame-rate counter is the first debugging tool for any game:

Python
fps_text = font.render(f"{clock.get_fps():.0f} FPS", True, (255, 255, 255))
screen.blit(fps_text, (10, 10))

If the number drops below your target, something in update or draw is too slow. Compare get_rawtime() with 1000 / FPS: when the raw time is near the budget, you are close to the limit.

Try it: a real clock

Clock works without a window, so you can see what its methods return. Here we call tick() with no frame rate, which measures time without sleeping (in a real game you pass 60 so it sleeps). Exact timings differ on every machine, so the example prints properties, not numbers.

Python What Clock.tick returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With tick(20) instead, each of those frames would last about 50 ms because Pygame would sleep for the rest of the frame budget.

get_ticks: the game's stopwatch

pygame.time.get_ticks() returns the number of milliseconds since pygame.init(). Store a timestamp, then compare it later: that is how cooldowns, delays and timers are built without blocking the loop.

Python
SHOOT_COOLDOWN = 300           # ms
last_shot = -SHOOT_COOLDOWN    # so the first shot is allowed

now = pygame.time.get_ticks()
if keys[pygame.K_SPACE] and now - last_shot >= SHOOT_COOLDOWN:
    fire_bullet()
    last_shot = now

Another classic: a message that disappears after two seconds.

Python
message_until = now + 2000     # show for 2 seconds
...
if pygame.time.get_ticks() < message_until:
    screen.blit(message_surface, (20, 20))

Try it: cooldown logic with a fake clock

The logic above does not depend on a real clock, so we can test it by passing the time in. This function decides whether a shot is allowed at each moment and shows that holding the button fires at a steady rate.

Python Weapon cooldown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Countdown and stopwatch formatting

Turning milliseconds into MM:SS is something you will do in almost every game:

Python
def format_time(ms):
    seconds, ms = divmod(ms, 1000)
    minutes, seconds = divmod(seconds, 60)
    return f"{minutes:02}:{seconds:02}.{ms // 100}"

Try it: a countdown

Here the countdown is driven by delta time, which is more robust than comparing absolute ticks when the game can be paused. A paused game simply stops adding dt.

Python Countdown driven by dt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

wait and delay

pygame.time.wait(ms) and pygame.time.delay(ms) pause the program. wait sleeps (kind to the CPU); delay is more accurate. Avoid both in the middle of the game loop: while the program sleeps it cannot process events, so the window freezes and the game feels unresponsive. Use timestamps or timers instead. They are fine at start-up or inside a quick tool.

Timers that post events

pygame.time.set_timer(event, millis) asks Pygame to put an event in the queue every millis milliseconds. That is ideal for spawning enemies or animating on a beat, and it needs no bookkeeping in the loop. Because it uses the event queue, we cover it in Custom Events and Timers.

Common mistakes

  • Calling clock.tick() more than once per frame: dt becomes meaningless.
  • Using time.sleep() in the loop: the window stops responding.
  • Dividing by dt when dt is 0 (possible on the very first frame): add a small guard.
  • Forgetting that get_ticks() continues while the game is paused: store a pause offset or use delta time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does clock.get_fps() return?

    It averages the last ten ticks. It is useful for an on-screen counter.
  2. 2. What is a good way to implement a weapon cooldown without freezing the game?

    Storing a timestamp lets the loop continue and handle events while waiting.
  3. 3. What is the difference between tick() and tick_busy_loop()?

    tick_busy_loop spins instead of sleeping, giving better accuracy at the price of CPU time.
  4. 4. Why avoid pygame.time.wait(1000) inside the loop?

    The program sleeps and cannot respond to the operating system.

Summary

  • Make one Clock, call tick(FPS) once per frame, use the result as dt.
  • get_fps() helps you debug performance; get_rawtime() shows the real work time.
  • get_ticks() timestamps drive cooldowns and temporary messages.
  • Pass a time value into logic so it can be tested without a window.
  • Avoid sleeping in the loop; use timers and timestamps.

Next: Event Handling