Identifying the slowest section of code
This is a process known as profiling and is covered in textbooks and (for standard Python) supported by various software tools. For the type of smaller embedded application likely to be running on MicroPython platforms the slowest function or method can usually be established by judicious use of the timing ticks group of functions documented in time. Code execution time can be measured in ms, us, or CPU cycles.
The following enables any function or method to be timed by adding an @timed_function decorator:
def timed_function(f, *args, **kwargs):
myname = str(f).split(' ')[1]
def new_func(*args, **kwargs):
t = time.ticks_us()
result = f(*args, **kwargs)
delta = time.ticks_diff(time.ticks_us(), t)
print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000))
return result
return new_func
Make use of const()
function
MicroPython provides a const() declaration. This works in a similar way to #define in C in that when the code is compiled to bytecode the compiler substitutes the numeric value for the identifier. This avoids a dictionary lookup at runtime. The argument to const() may be anything which, at compile time, evaluates to an integer e.g. 0x100 or 1 « 8.
a=const(20)
Use less and short variable names
This is self explanatory. Try to use as low number of variables as possible. Use short string for naming the variable.
Use local scope instead of global scope
Don’t do:
from machine import Pin
led=Pin(2,Pin.OUT)
def some_function():
for x in range(0,100):
led.value(not led.value())
some_function()
Do this:
from machine import Pin
def some_function():
led=Pin(2,Pin.OUT)
for x in range(0,100):
led.value(not led.value())
some_function()
Use reference to global objects in local scope
import time
from machine import Pin
def f():
led=Pin(2,Pin.OUT)
s=time.sleep
while True:
led.value(not led.value())
s(1)
Don’t use *
and **
args in function
When defining a function don’t use * and ** in function definition. This increases the lookup time.
Use compiled program in .mpy format
This is equivalent to .pyc for standard python. This reduces the compilation time.
ProTips: Freeze your script into the firmware in order to maximize the efficiency.