Timing Drawing Speed
If you are writing a video game and want fast drawing times for objects on the screen, there are several different algorithms you can try. You can use the MicroPython time_us
function to
record the time before and after you call a drawing function and return the difference
to get an idea of the time saved in different versions of your drawing functions.
Sample Function Timer Code
Sample Function Code
1 2 3 4 5 6 |
|
MicroPython also supports the ticks_cpu()
function which could return a smaller granularity
for precise time measurements. However, on the Raspberry Pi implementation, the results are exactly
the same as the ticks_us()
function.
Comparing Two Circle Drawing Algorithms
In the following code, we compare two circle drawing algorithms.
- Row Scanner Method - this method scans each pixel in the square around the circle and turns it on if the pixel is within a distance range. It must calculate the distance of each pixel and compare
- that distance to both the inside and outside distances. The time-consuming operations are to calculate the squares of the x and y distances.
- Point Draw Method - this method walks around the circle and for each degree, it draws a single pixel at the edge of the circle. Each point uses the
sine()
andcosine()
functions to calculate the x and y distance from the center of the circle to that point.
For small circles, it is very inefficient to calculate all 360 points. Scanning all the points in a 5X5 grid only takes 25 calculations. However, the larger the circle becomes, the more points there are to calculate in the row scanner method. A 20X20 circle will need to run the distance calculation 400 times.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
|
Challenge
- Write a program that compares drawing speed for various sizes of circles.
- Modify the circle function to use the most efficient algorithm
- If you have a small circle, how many points do you need to not make the circle appear broken? Try changing the number of points calculated in the line
`for theta in range(0, 360, 2):
. Can you dynamically change the number of points skipped as the circle becomes smaller? - Can you add a parameter to the circle function that only draws every 3rd point?