bbcmicrobit / micropython

Port of MicroPython for the BBC micro:bit
https://microbit-micropython.readthedocs.io
Other
603 stars 284 forks source link

Saving memory and running faster : does this need documenting? #639

Open rhubarbdog opened 5 years ago

rhubarbdog commented 5 years ago

Hi, whilst developing a game i was running into OOM Memory Error so I tried a few things to get my desired new modification into the game and was surprised when I got a huge improvement in running speed. To research the subtle differences I wrote the following sample program

from microbit import *
import time

begin = time.ticks_us()
for _ in range(1000):
    pin0.read_digital()

elapse = time.ticks_diff(time.ticks_us(), begin)
print(elapse)

I then changed line 1 to read from microbit import pin0. I repeated the experiment with line 1 reading import microbit

from microbit import *16.1ms
from microbit import pin013.9ms
import microbit18.4ms

Because these results differed from what i expected. I repeated the experiment with a dictionary of pins which is more like my game, so the 3 programs are a version of

from microbit import *
import time

PINS = { 0 : pin0, }

begin = time.ticks_us()
for _ in range(1000):
    PINS[0].read_digital()

elapse = time.ticks_diff(time.ticks_us(), begin)
print(elapse)
from microbit import *24ms
from microbit import pin016.9ms
import microbit17.3ms

Are these time differences and associated memory usage with the 3 versions of importing a module worthy of documentation. Any user who develops a considerable micropython program on the microbit will probably run into OOM Memory Error. Also It's always nice to get a program running faster, it can always be slowed down with a sleep() statement