”;
In this chapter, we shall find out how efficient is the graphics engine. This can be done by adding a large number of graphics instructions to the canvas of a Kivy object.
The program given below measures the time required by the graphics engine to draw ten thousand rectangles at random positions and with randomly chosen color value. Thus it will give an evaluation of how much stress the canvas can sustain.
Syntax
A rectangle instruction is drawn on the canvas of any Kivy widget with the following syntax −
with self.root.canvas: Color(r,g,b,a) Rectangle(pos, size)
We shall generate random values for RGB as well as x and y coordinates for the rectangle and display 10, 000 rectangles. The time taken for it is calculated by the perf_counter() function.
t1=perf_counter() with self.root.canvas: for i in range(10000): Color(r,g,b,a) Rectangle(pos, size) t2=perf_counter()
The time required to draw will be “t2 – t1”. It will be displayed on the title bar of the Kivy app window.
Example
The complete program is as follows −
from kivy.app import App from kivy.graphics import * from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from random import random as r from time import perf_counter from kivy.core.window import Window Window.size = (720, 400) class StresstestApp(App): def add_rects(self, *args): self.t1 = perf_counter() with self.root.canvas: for i in range(10000): Color(r(), 1, 1, mode=''hsv'') Rectangle( pos=(r() * self.root.width + self.root.x, r() * self.root.height + self.root.y), size=(20, 20) ) self.t2 = perf_counter() self.title = str(self.t2 - self.t1) + "Sec. to draw 10000 rectangles" def build(self): main = GridLayout(cols=1) self.root = FloatLayout(size=(Window.width, 100)) self.btn1 = Button( text=''start'', size_hint=(1, None), pos_hint={''center_x'': .5, ''center_y'': .1} ) self.btn1.bind(on_press=self.add_rects) self.root.add_widget(self.btn1) main.add_widget(self.root) return main StresstestApp().run()
Output
Run the program and click the “start” button.
You will get the time taken displayed on the title bar as shown in the following figure −
”;