1

I'm running a small game in pygame for which I need a constant delay between each iteration of the main loop. Altough I locked the FPS count at 60 with pygame.Clock.tick_busy_loop(), I observe a variation in delay (around 4 milliseconds per loop). One of my function should be bugged, but I have troubles finding which one.

I used a %prun on my main loop with Ipython, and these are the results :

         2264 function calls in 5.439 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      322    4.401    0.014    4.401    0.014 {method 'tick' of 'Clock' objects}
      322    0.730    0.002    0.730    0.002 {pygame.display.flip}
        1    0.228    0.228    0.228    0.228 {pygame.base.quit}
        1    0.034    0.034    0.034    0.034 {method 'blit' of 'pygame.Surface' objects}
        1    0.028    0.028    5.439    5.439 main.py:9(main)
      323    0.014    0.000    0.014    0.000 {pygame.event.get}
      323    0.002    0.000    0.016    0.000 lib.py:26(getInput)
      322    0.001    0.000    0.036    0.000 lib.py:80(checkEventType)
      322    0.001    0.000    0.035    0.000 lib.py:91(instructions)
      322    0.000    0.000    0.000    0.000 {method 'get_time' of 'Clock' objects}
        1    0.000    0.000    5.439    5.439 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {pygame.mixer.stop}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        2    0.000    0.000    0.000    0.000 {ord}

Is there something in here that could explain a 2-5 millisecond change in delay between each iteration?

Crolle
  • 822
  • 3
  • 10
  • 20
  • Start by using `cProfile` from the command-line to get a more detailed output: http://stackoverflow.com/a/7693928/1156707 – Louis Thibault Dec 02 '13 at 15:47
  • This may just be an implementation detail. The documentation for `tick_busy_loop` says, "the function will delay to keep the game running slower than the given ticks per second." There's no guarantee that it will be as close to ticks per second as possible; Pygame could slow you down to 5 FPS and still keep its promise. – Kevin Dec 02 '13 at 16:01

2 Answers2

1

Your program isn't the only program on computer. System has to run other programs in the same time. Sometimes it is done faster, sometimes slower. 2-5 ms is so little to worry about.

furas
  • 134,197
  • 12
  • 106
  • 148
1

You would probably also want to look into using pygame.time.Clock.tick() rather than pygame.Clock.tick_busy_loop():

http://www.pygame.org/docs/ref/time.html#pygame.time.Clock.tick

Note that this function uses SDL_Delay function which is not accurate on every platform, but does not use much cpu. Use tick_busy_loop if you want an accurate timer, and don’t mind chewing cpu.

Unless, of course, you are very strict about keeping the framerate at 60.

Marcus Møller
  • 618
  • 6
  • 8