As like of pygame i want to limit the frame rate of a loop. Pygame provide the pygame.time.Clock.tick() way to do it:
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.
But how to do it natively in python ?
To illustrate:
import time
max_frames = 125 # 25*5
current_frame = 1
while current_frame <= max_frames:
print('frame', time.clock(), current_frame)
current_frame += 1
produce:
('frame', 0.01, 1)
('frame', 0.01, 2)
('frame', 0.01, 3)
[...]
('frame', 0.01, 124)
('frame', 0.01, 125)
I would like 25 frames per seconds, so
('frame', 0.01, 1)
('frame', 0.05, 2)
('frame', 0.08, 3)
[...]
('frame', 4.98, 124)
('frame', 5.00, 125)
You could just use time.sleep(1./25) to wait 1/25 of a second.
while current_frame <= max_frames:
# ... do stuff
time.sleep(1./25)
Note that will will always wait that time additionally to whatever time the loop body takes anyway. Alternatively, memorize the last execution time and wait until this time + 1/25 of a second.
while current_frame <= max_frames:
start = time.time()
# ... do stuff that might take significant time
time.sleep(max(1./25 - (time.time() - start), 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With