Precise framerate calculation, scheduling and framerate limiting.
The tick and get_fps functions can be used in conjunction to fulfil most games’ basic requirements:
from pyglet import clock
while True:
dt = clock.tick()
# ... update and render ...
print 'FPS is %f' % clock.get_fps()
The dt
value returned gives the number of seconds (as a float) since the
last “tick”.
The get_fps function averages the framerate over a sliding window of
approximately 1 second. (You can calculate the instantaneous framerate by
taking the reciprocal of dt
).
Always remember to tick the clock!
The framerate can be limited:
clock.set_fps_limit(60)
This causes Clock
to sleep during each tick in an attempt to keep the
number of ticks (frames) per second below 60.
The implementation uses platform-dependent high-resolution sleep functions to achieve better accuracy with busy-waiting than would be possible using just the time module.
You can schedule a function to be called every time the clock is ticked:
def callback(dt):
print '%f seconds since last callback' % dt
clock.schedule(callback)
The schedule_interval method causes a function to be called every “n” seconds:
clock.schedule_interval(callback, .5) # called twice a second
The schedule_once method causes a function to be called once “n” seconds in the future:
clock.schedule_once(callback, 5) # called in 5 seconds
All of the schedule methods will pass on any additional args or keyword args you specify to the callback function:
def animate(dt, velocity, sprite):
sprite.position += dt * velocity
clock.schedule(animate, velocity=5.0, sprite=alien)
You can cancel a function scheduled with any of these methods using unschedule:
clock.unschedule(animate)
The ClockDisplay class provides a simple FPS counter. You should create an instance of ClockDisplay once during the application’s start up:
fps_display = clock.ClockDisplay()
Call draw on the ClockDisplay object for each frame:
fps_display.draw()
There are several options to change the font, color and text displayed within the __init__ method.
The clock functions are all relayed to an instance of Clock
which is
initialised with the module. You can get this instance to use directly:
clk = clock.get_default()
You can also replace the default clock with your own:
myclk = clock.Clock() clock.set_default(myclk)
Each clock maintains its own set of scheduled functions and FPS limiting/measurement. Each clock must be “ticked” separately.
Multiple and derived clocks potentially allow you to separate “game-time” and “wall-time”, or to synchronise your clock to an audio or video stream instead of the system clock.
Clock
(fps_limit=None, time_function=<built-in function time>)¶Class for calculating and limiting framerate, and for calling scheduled functions.
call_scheduled_functions
(dt)¶Call scheduled functions that elapsed on the last update_time.
New in version 1.2.
Parameters: | dt (float) – The elapsed time since the last update to pass to each scheduled function. This is not used to calculate which functions have elapsed. |
---|---|
Return type: | bool |
Returns: | True if any functions were called, otherwise False. |
get_fps
()¶Get the average FPS of recent history.
The result is the average of a sliding window of the last “n” frames, where “n” is some number designed to cover approximately 1 second.
Return type: | float |
---|---|
Returns: | The measured frames per second. |
get_fps_limit
()¶Get the framerate limit.
Return type: | float |
---|---|
Returns: | The framerate limit previously set in the constructor or set_fps_limit, or None if no limit was set. |
get_sleep_time
(sleep_idle)¶Get the time until the next item is scheduled.
This method considers all scheduled items and the current
fps_limit
, if any.
Applications can choose to continue receiving updates at the maximum framerate during idle time (when no functions are scheduled), or they can sleep through their idle time and allow the CPU to switch to other processes or run in low-power mode.
If sleep_idle is True
the latter behaviour is selected, and
None
will be returned if there are no scheduled items.
Otherwise, if sleep_idle is False
, a sleep time allowing
the maximum possible framerate (considering fps_limit
) will
be returned; or an earlier time if a scheduled function is ready.
Parameters: | sleep_idle (bool) – If True, the application intends to sleep through its idle time; otherwise it will continue ticking at the maximum frame rate allowed. |
---|---|
Return type: | float |
Returns: | Time until the next scheduled event in seconds, or None
if there is no event scheduled. |
New in version 1.1.
schedule
(func, *args, **kwargs)¶Schedule a function to be called every frame.
The function should have a prototype that includes dt
as the
first argument, which gives the elapsed time, in seconds, since the
last clock tick. Any additional arguments given to this function
are passed on to the callback:
def callback(dt, *args, **kwargs):
pass
Parameters: | func (function) – The function to call each frame. |
---|
schedule_interval
(func, interval, *args, **kwargs)¶Schedule a function to be called every interval seconds.
Specifying an interval of 0 prevents the function from being called again (see schedule to call a function as often as possible).
The callback function prototype is the same as for schedule.
Parameters: |
|
---|
schedule_interval_soft
(func, interval, *args, **kwargs)¶Schedule a function to be called every interval seconds, beginning at a time that does not coincide with other scheduled events.
This method is similar to schedule_interval, except that the clock will move the interval out of phase with other scheduled functions so as to distribute CPU more load evenly over time.
This is useful for functions that need to be called regularly,
but not relative to the initial start time. pyglet.media
does this for scheduling audio buffer updates, which need to occur
regularly – if all audio updates are scheduled at the same time
(for example, mixing several tracks of a music score, or playing
multiple videos back simultaneously), the resulting load on the
CPU is excessive for those intervals but idle outside. Using
the soft interval scheduling, the load is more evenly distributed.
Soft interval scheduling can also be used as an easy way to schedule graphics animations out of phase; for example, multiple flags waving in the wind.
New in version 1.1.
Parameters: |
|
---|
schedule_once
(func, delay, *args, **kwargs)¶Schedule a function to be called once after delay seconds.
The callback function prototype is the same as for schedule.
Parameters: |
|
---|
set_fps_limit
(fps_limit)¶Set the framerate limit.
The framerate limit applies only when a function is scheduled for every frame. That is, the framerate limit can be exceeded by scheduling a function for a very small period of time.
Parameters: | fps_limit (float) – Maximum frames per second allowed, or None to disable limiting. |
---|
Warning
Deprecated. Use pyglet.app.run and schedule_interval instead.
tick
(poll=False)¶Signify that one frame has passed.
This will call any scheduled functions that have elapsed.
Parameters: | poll (bool) – If True, the function will call any scheduled functions but will not sleep or busy-wait for any reason. Recommended for advanced applications managing their own sleep timers only. Since pyglet 1.1. |
---|---|
Return type: | float |
Returns: | The number of seconds since the last “tick”, or 0 if this was the first frame. |
unschedule
(func)¶Remove a function from the schedule.
If the function appears in the schedule more than once, all occurrences are removed. If the function was not scheduled, no error is raised.
Parameters: | func (function) – The function to remove from the schedule. |
---|
update_time
()¶Get the elapsed time since the last call to update_time.
This updates the clock’s internal measure of time and returns the difference since the last update (or since the clock was created).
New in version 1.2.
Return type: | float |
---|---|
Returns: | The number of seconds since the last update_time, or 0 if this was the first time it was called. |
MIN_SLEEP
= 0.005¶The minimum amount of time in seconds this clock will attempt to sleep for when framerate limiting. Higher values will increase the accuracy of the limiting but also increase CPU usage while busy-waiting. Lower values mean the process sleeps more often, but is prone to over-sleep and run at a potentially lower or uneven framerate than desired.
SLEEP_UNDERSHOOT
= 0.004¶The amount of time in seconds this clock subtracts from sleep values to compensate for lazy operating systems.
ClockDisplay
(font=None, interval=0.25, format=’%(fps).2f’, color=(0.5, 0.5, 0.5, 0.5), clock=None)¶Display current clock values, such as FPS.
This is a convenience class for displaying diagnostics such as the framerate. See the module documentation for example usage.
Variables: | label (pyglet.font.Text) – The label which is displayed. |
---|
Warning
Deprecated. This class presents values that are often misleading, as they reflect the rate of clock ticks, not displayed framerate. Use pyglet.window.FPSDisplay instead.
draw
()¶Method called each frame to render the label.
unschedule
()¶Remove the display from its clock’s schedule.
ClockDisplay
uses Clock.schedule_interval to periodically update
its display label. Even if the ClockDisplay is not being used any
more, its update method will still be scheduled, which can be a
resource drain. Call this method to unschedule the update method
and allow the ClockDisplay to be garbage collected.
New in version 1.1.
update_text
(dt=0)¶Scheduled method to update the label text.
get_default
()¶Return the Clock
instance that is used by all module-level
clock functions.
Return type: | Clock |
---|---|
Returns: | The default clock. |
get_fps
()¶Return the current measured FPS of the default clock.
Return type: | float |
---|
get_fps_limit
()¶Get the framerate limit for the default clock.
Returns: | The framerate limit previously set by set_fps_limit, or None if no limit was set. |
---|
get_sleep_time
(sleep_idle)¶Get the time until the next item is scheduled on the default clock.
See Clock.get_sleep_time for details.
Parameters: | sleep_idle (bool) – If True, the application intends to sleep through its idle time; otherwise it will continue ticking at the maximum frame rate allowed. |
---|---|
Return type: | float |
Returns: | Time until the next scheduled event in seconds, or None
if there is no event scheduled. |
New in version 1.1.
schedule
(func, *args, **kwargs)¶Schedule ‘func’ to be called every frame on the default clock.
The arguments passed to func are dt
, followed by any *args
and
**kwargs
given here.
Parameters: | func (function) – The function to call each frame. |
---|
schedule_interval
(func, interval, *args, **kwargs)¶Schedule ‘func’ to be called every ‘interval’ seconds on the default clock.
The arguments passed to ‘func’ are ‘dt’ (time since last function call),
followed by any *args
and **kwargs
given here.
Parameters: |
|
---|
schedule_interval_soft
(func, interval, *args, **kwargs)¶Schedule ‘func’ to be called every ‘interval’ seconds on the default clock, beginning at a time that does not coincide with other scheduled events.
The arguments passed to ‘func’ are ‘dt’ (time since last function call),
followed by any *args
and **kwargs
given here.
See: | Clock.schedule_interval_soft |
---|
New in version 1.1.
Parameters: |
|
---|
schedule_once
(func, delay, *args, **kwargs)¶Schedule ‘func’ to be called once after ‘delay’ seconds (can be
a float) on the default clock. The arguments passed to ‘func’ are
‘dt’ (time since last function call), followed by any *args
and
**kwargs
given here.
If no default clock is set, the func is queued and will be scheduled on the default clock as soon as it is created.
Parameters: |
|
---|
set_default
(default)¶Set the default clock to use for all module-level functions.
By default an instance of Clock
is used.
Parameters: | default (Clock) – The default clock to use. |
---|
set_fps_limit
(fps_limit)¶Set the framerate limit for the default clock.
Parameters: | fps_limit (float) – Maximum frames per second allowed, or None to disable limiting. |
---|
Warning
Deprecated. Use pyglet.app.run and schedule_interval instead.
test_clock
()¶tick
(poll=False)¶Signify that one frame has passed on the default clock.
This will call any scheduled functions that have elapsed.
Parameters: | poll (bool) – If True, the function will call any scheduled functions but will not sleep or busy-wait for any reason. Recommended for advanced applications managing their own sleep timers only. Since pyglet 1.1. |
---|---|
Return type: | float |
Returns: | The number of seconds since the last “tick”, or 0 if this was the first frame. |
unschedule
(func)¶Remove ‘func’ from the default clock’s schedule. No error is raised if the func was never scheduled.
Parameters: | func (function) – The function to remove from the schedule. |
---|