Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Table of contents
Keeping track of time
Calling functions periodically
Sprite movement techniques
The frame rate
Displaying the frame rate 
User-defined clocks
Frequently Asked Questions 
Is pyglet open-source?
What is pyglet used for?
Does pyglet work on Mac?
Last Updated: Mar 27, 2024

Keeping track of time in pyglet

Author Tarun Singh
0 upvote
Master Python: Predicting weather forecasts
Ashwin Goyal
Product Manager @


In this blog, we will discuss keeping track of time in pyglet. But first, we need to know what is pyglet? So, pyglet is a Python library that provides an object-oriented application programming interface for developing games and other multimedia applications. Pyglet is a BSD-licensed program that runs on Microsoft Windows, macOS, and Linux. 

In this blog, we will learn how to keep track of time in pyglet, so let's dive right in.

Keeping track of time

The clock module in pyglet allows you to plan functions to run frequently or once in the future. There are also some valuable utilities for calculating and displaying the frame rate of the program. We will look at some useful functions to keep track of time in pyglet in the blog.  

Calling functions periodically

An application event loop is used to execute pyglet applications:


This function does not return until all program windows have been closed after being called. You might be wondering how to run code while the application is executing. Typical apps only need to run code in three situations:

  1.  A user input event has been generated (such as a mouse movement or key push). In this situation, the relevant code can be connected to the window as an event handler.
  2. The location or parameters of an object must be updated in animation or another time-dependent system. This will be referred to as a "periodic" event.
  3. A particular time has passed, signaling that an action has been completed or dialogue can be dismissed automatically. This will be a "one-shot" event.

To have a function called periodically, such as once every 0.1 seconds:

def update(dt):
   # ...
pyglet.clock.schedule_interval(update, 0.1)


The dt, or delta time, the parameter indicates how many "wall clock" seconds had passed since the function's last call (or if it's the first period when the function was scheduled). This may be more or less than the required interval due to latency, load, and timer inaccuracy. Please note that the dt parameter is continuously supplied to scheduled functions, so expect it while writing functions even if you don't need it.

Scheduling functions with a specified interval is ideal for animation, physics simulation, and game state updates. Pyglet ensures that the program uses no more resources than are required to complete the scheduled tasks on time.

Schedule all your update functions for at least the time your application or game requires, this method is contrary to what other toolkits prefer( they use "limiting the frame rate"). Let's take an example to suppose we want to limit the frames rendered per second to 60. Hence the interval given to schedule interval() would be 1/60.0. (or more). 

def standard(dt):
    # ...

If you're conducting a benchmark, you might wish to disable sync because pyglet window buffer swaps are synchronized with the display refresh rate by default.


Use schedule_once() for one-time events: 

def remove_dialog(dt):
    # ...
# Remove  the dialog after 5 seconds.
pyglet.clock.schedule_once(remove_dialog, 5.0)


Use pyglet. Clock.unschedule to prevent a scheduled function from being called, such as canceling a periodic function (). This could be beneficial if you want to start a function on a schedule when a user enters a specific value and then unscheduled it when another value is entered.

Sprite movement techniques

Every scheduled function receives a dt parameter, which specifies the amount of time since the previous invocation. This parameter can be used to integrate numerically.

A non-accelerating particle with velocity v, for example, will move a certain distance over a change in time dt. This distance is determined using the formula v*dt. Similarly, a particle moving at a constant speed will experience a velocity change of a*dt.

The code below depicts an easy and convenient way to move the sprite along with the screen at exactly 10 pixes per second:

sprite = pyglet.sprite.Sprite(image)
sprite.dx = 10.0

def upgrade(dt):
    sprite.x += sprite.dx * dt
pyglet.clock.schedule_interval(upgrade, 1/60.0) 
# upgrade at 60Hz


This is a reliable method for simple sprite movement because the velocity remains constant, independent of the computer's speed or load.          


Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job

The frame rate

The number of times the display is updated every second, or frames-per-second, is a practical way to check game performance on PC's. With a single function call, you may determine the FPS of your application:



The value returned is more valuable than just obtaining the reciprocal of dt from a period function.

Displaying the frame rate 

An easy way to track your application's performance is to track the frame rate at which it is operating. It is not a good idea to print the frame rate onto the console while the application is running as it affects the application's performance. Not to worry, pyglet got you covered as it provides FPSDisplay class for displaying the frame rate with very little effort.

fps_display = pyglet.window.FPSDisplay(window=window)
def when_drawing():

The frame rate is displayed in a semi-transparent big text in the bottom-left corner of the window by default. 

User-defined clocks

The system clock determines the time in pyglet's default clock (i.e., time.time()). However, separate clocks can be constructed to allow you to use a different time source. This can be used to create a particular "game time" from real-world time or synchronize with a network time source or a sound device.

Each clock_* function is an alias for a global instance of Clock's methods. You can create or subclass your Clock, which will keep track of its schedule and calculate framerate. 

Frequently Asked Questions 

Is pyglet open-source?

Pyglet is released under the BSD(Berkeley Software Distribution) open-source license, allowing it to be used in commercial and open-source projects with few restrictions.

What is pyglet used for?

Python's pyglet module is a cross-platform windowing and multimedia library for creating games and other visually rich applications. Windowing, user interface event management, gaming controllers and joysticks, OpenGL graphics, picture, and video loading, and sound and music playback are all supported.

Does pyglet work on Mac?

Yes, pyglet work on macOS. Features like user interface, event management, joysticks, OpenGL graphics, loading photos, movies, and sound and music playback are all supported.


In this article, we have extensively discussed how to keep track of time in pyglet; further, we have discussed its functions and addressed frame rate and user-defined clocks with coded examples.

After reading about keeping track of time in pyglet, are you not feeling excited to read/explore more articles on the topic of pyglet framework? Don't worry; Coding Ninjas has you covered. To learn, see Operating SystemUnix File SystemFile System Routing, and File Input/Output.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc.. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Previous article
The pyglet event framework
Next article
Creating an OpenGL Context
Live masterclass