Performance Statistics#

../../_images/performance_statistics1.png

Arcade includes performance monitoring tools to help you optimize your game. This example demonstrates the following performance api features:

If you do not want to display graphs in your game window, you can use arcade.print_timings() to print out the count and average time for all dispatched events with the function. The output looks like this:

Event          Count Average Time
-------------- ----- ------------
on_activate        1       0.0000
on_resize          1       0.0000
on_show            1       0.0000
on_update         59       0.0000
on_expose          1       0.0000
on_draw           59       0.0021
on_mouse_enter     1       0.0000
on_mouse_motion  100       0.0000

See Performance Information for more information about the performance api.

performance_statistics.py#
  1"""
  2Performance Statistic Display Example
  3
  4This example demonstrates how to use a few performance profiling tools
  5built into arcade:
  6
  7* arcade.enable_timings
  8* arcade.PerfGraph
  9* arcade.get_fps
 10* arcade.print_timings
 11* arcade.clear_timings
 12
 13A large number of sprites bounce around the screen to produce load. You
 14can adjust the number of sprites by changing the COIN_COUNT constant.
 15
 16Artwork from https://kenney.nl
 17
 18If Python and Arcade are installed, this example can be run from the
 19command line with:
 20python -m arcade.examples.performance_statistics
 21"""
 22import random
 23from typing import Optional
 24
 25import arcade
 26
 27# --- Constants ---
 28SPRITE_SCALING_COIN = 0.25
 29SPRITE_NATIVE_SIZE = 128
 30SPRITE_SIZE = int(SPRITE_NATIVE_SIZE * SPRITE_SCALING_COIN)
 31
 32SCREEN_WIDTH = 800
 33SCREEN_HEIGHT = 600
 34SCREEN_TITLE = "Performance Statistics Display Example"
 35
 36# Size of performance graphs and distance between them
 37GRAPH_WIDTH = 200
 38GRAPH_HEIGHT = 120
 39GRAPH_MARGIN = 5
 40
 41COIN_COUNT = 1500
 42
 43
 44# Turn on tracking for the number of event handler
 45# calls and the average execution time of each type.
 46arcade.enable_timings()
 47
 48
 49class Coin(arcade.Sprite):
 50    """ Our coin sprite class """
 51    def update(self):
 52        """ Update the sprite. """
 53        # Setting the position is faster than setting x & y individually
 54        self.position = (
 55            self.position[0] + self.change_x,
 56            self.position[1] + self.change_y
 57        )
 58
 59        # Bounce the coin on the edge of the window
 60        if self.position[0] < 0:
 61            self.change_x *= -1
 62        elif self.position[0] > SCREEN_WIDTH:
 63            self.change_x *= -1
 64        if self.position[1] < 0:
 65            self.change_y *= -1
 66        elif self.position[1] > SCREEN_HEIGHT:
 67            self.change_y *= -1
 68
 69
 70class MyGame(arcade.Window):
 71    """ Our custom Window Class"""
 72
 73    def __init__(self):
 74        """ Initializer """
 75        # Call the parent class initializer
 76        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
 77
 78        # Variables to hold game objects and performance info
 79        self.coin_list: Optional[arcade.SpriteList] = None
 80        self.perf_graph_list: Optional[arcade.SpriteList] = None
 81        self.fps_text: Optional[arcade.Text] = None
 82        self.frame_count: int = 0  # for tracking the reset interval
 83
 84        arcade.set_background_color(arcade.color.AMAZON)
 85
 86    def add_coins(self, amount):
 87
 88        # Create the coins
 89        for i in range(amount):
 90            # Create the coin instance
 91            # Coin image from kenney.nl
 92            coin = Coin(":resources:images/items/coinGold.png", SPRITE_SCALING_COIN)
 93
 94            # Position the coin
 95            coin.position = (
 96                random.randrange(SPRITE_SIZE, SCREEN_WIDTH - SPRITE_SIZE),
 97                random.randrange(SPRITE_SIZE, SCREEN_HEIGHT - SPRITE_SIZE)
 98            )
 99
100            coin.change_x = random.randrange(-3, 4)
101            coin.change_y = random.randrange(-3, 4)
102
103            # Add the coin to the lists
104            self.coin_list.append(coin)
105
106    def setup(self):
107        """ Set up the game and initialize the variables. """
108
109        # Sprite lists
110        self.coin_list = arcade.SpriteList(use_spatial_hash=False)
111
112        # Create some coins
113        self.add_coins(COIN_COUNT)
114
115        # Create a sprite list to put the performance graphs into
116        self.perf_graph_list = arcade.SpriteList()
117
118        # Calculate position helpers for the row of 3 performance graphs
119        row_y = self.height - GRAPH_HEIGHT / 2
120        starting_x = GRAPH_WIDTH / 2
121        step_x = GRAPH_WIDTH + GRAPH_MARGIN
122
123        # Create the FPS performance graph
124        graph = arcade.PerfGraph(GRAPH_WIDTH, GRAPH_HEIGHT, graph_data="FPS")
125        graph.position = starting_x, row_y
126        self.perf_graph_list.append(graph)
127
128        # Create the on_update graph
129        graph = arcade.PerfGraph(GRAPH_WIDTH, GRAPH_HEIGHT, graph_data="on_update")
130        graph.position = starting_x + step_x, row_y
131        self.perf_graph_list.append(graph)
132
133        # Create the on_draw graph
134        graph = arcade.PerfGraph(GRAPH_WIDTH, GRAPH_HEIGHT, graph_data="on_draw")
135        graph.position = starting_x + step_x * 2, row_y
136        self.perf_graph_list.append(graph)
137
138        # Create a Text object to show the current FPS
139        self.fps_text = arcade.Text(
140            f"FPS: {arcade.get_fps(60):5.1f}",
141            10, 10, arcade.color.BLACK, 22
142        )
143
144    def on_draw(self):
145        """ Draw everything """
146
147        # Clear the screen
148        self.clear()
149
150        # Draw all the coin sprites
151        self.coin_list.draw()
152
153        # Draw the graphs
154        self.perf_graph_list.draw()
155
156        # Get & draw the FPS for the last 60 frames
157        if arcade.timings_enabled():
158            self.fps_text.value = f"FPS: {arcade.get_fps(60):5.1f}"
159            self.fps_text.draw()
160
161    def on_update(self, delta_time):
162        """ Update method """
163        self.frame_count += 1
164
165        # Print and clear timings every 60 frames
166        if self.frame_count % 60 == 0:
167            arcade.print_timings()
168            arcade.clear_timings()
169
170        # Move the coins
171        self.coin_list.update()
172
173    def on_key_press(self, symbol: int, modifiers: int):
174        if symbol == arcade.key.SPACE:
175            if arcade.timings_enabled():
176                arcade.disable_timings()
177            else:
178                arcade.enable_timings()
179
180
181def main():
182    """ Main function """
183    window = MyGame()
184    window.setup()
185    arcade.run()
186
187
188if __name__ == "__main__":
189    main()