Observation regarding imports and performance

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
josie87
Posts: 24
Joined: Tue Jun 30, 2015 2:46 pm

Observation regarding imports and performance

Post by josie87 » Mon Nov 30, 2015 2:23 pm

Hello,

I was just playing with the well known synthetic uPy benchmark:

Code: Select all

@micropython.viper
def performanceTest():
    millis = pyb.millis
    endTime = int(millis()) + 10000
    count = 0
    while int(millis()) < endTime:
        count += 1
    print("Count: ", count)
performanceTest()
Score: 5.433.881

Code: Select all

from pyb import millis
@micropython.viper
def performanceTest():
    #millis = pyb.millis
    endTime = int(millis()) + 10000
    count = 0
    while int(millis()) < endTime:
        count += 1
    print("Count: ", count)
performanceTest()
Score: 3.033.640

Code: Select all

@micropython.viper
def performanceTest():
    #millis = pyb.millis
    from pyb import millis
    endTime = int(millis()) + 10000
    count = 0
    while int(millis()) < endTime:
        count += 1
    print("Count: ", count)
performanceTest()
Score: 5.433.740

I get the same behaviour when using @micropython.native or no decorator.

My current strategy is to put my imports on top of the file, since its more readable.

Is the conclusion that uPy is usually faster when placing the imports inside the function/method?

Btw: Tested on my STM32F4 Discovery (I own a pyboard, but borrowed it to my brother). Since the chip is the same it should show similar performance.

pfalcon
Posts: 1155
Joined: Fri Feb 28, 2014 2:05 pm

Re: Observation regarding imports and performance

Post by pfalcon » Mon Nov 30, 2015 4:17 pm

Is the conclusion that uPy is usually faster when placing the imports inside the function/method?
Nope, that conclusion is wrong, or more exactly, it's sideways. MicroPython (and whole lot of other scripting languages) have more performance when using local variables, than with globals (that's because global variables are accessed by name, while locals are usually optimized to be access by stack index). If you do import within function, you just put module object into local variable.

So, if you really need to have more performance, then "millis = pyb.millis" (like shown commented in your code) should be enough, and is the clearest way to do it.
Awesome MicroPython list
Pycopy - A better MicroPython https://github.com/pfalcon/micropython
MicroPython standard library for all ports and forks - https://github.com/pfalcon/micropython-lib
More up to date docs - http://pycopy.readthedocs.io/

josie87
Posts: 24
Joined: Tue Jun 30, 2015 2:46 pm

Re: Observation regarding imports and performance

Post by josie87 » Tue Dec 01, 2015 7:07 am

Thanks

Post Reply