Labs / MicroPython tutorials / 01 Introduction to MicroPython Language — Draft Document Tutorial

How to Speed Up the Operation of MicroPython

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents

I. Optimization Steps

We can compare the code optimization process of MicroPython to "the steps to speed up a bicycle": first identify the core reasons why the bicycle runs slowly (such as flat tires or a laggy chain), then start with simple adjustments (inflating tires, lubricating the chain), and finally consider replacing high-end parts (lightweight frame, carbon fiber wheels). The code optimization of MicroPython also follows the order of "from simple to complex, from software to hardware", which can achieve the maximum performance improvement at the lowest cost and avoid wasting time by getting bogged down in complex low-level optimization from the very beginning.

Before starting the optimization, let's first understand several core basic concepts:

The process of developing high-performance code consists of the following phases, which shall be executed in the listed order:

  1. Identify the slowest parts in the code (profiling): This is the first and most critical step of optimization — if you optimize blindly, you may spend a lot of time optimizing code that is already fast, which is completely meaningless. We use the timing feature of the utime module to measure the execution time of each function and find the "performance bottleneck" that takes the longest time.
  2. Improving the Efficiency of Python Code (Basic Optimization): Without changing the execution logic of the code, optimize the writing style of Python code (for example, using list comprehensions instead of for loops, using local variables instead of global variables — local variables are accessed faster in MicroPython, reducing unnecessary function calls, etc.). This step is the simplest and can solve most performance problems.
  3. Use the native code emitter (intermediate optimization): If performance is still insufficient, use MicroPython's @micropython.native decorator to compile the function into native machine code, which will significantly improve execution speed with almost no code modifications required.
  4. Use the Viper code emitter (advanced optimization): if the code is still not fast enough after being natively compiled, use the @micropython.viper decorator, which can make the code execution speed close to that of C language, but note that there are syntax restrictions (for example, complex Python data structures cannot be used).
  5. Use mpy-cross to compile into bytecode (pre-compilation optimization): If the loading time of the script on its first run is still long after the previous optimizations (especially for large scripts), use mpy-cross on your computer to pre-. py files into. mpy bytecode files and then upload them to the device. This step does not require modifying the code, only changes the file loading method, and can significantly reduce the compilation overhead on the device.
  6. Use hardware-specific optimization (ultimate optimization): This is the final step, which utilizes the hardware peripherals of the microcontroller to replace software simulation, such as using hardware DMA to transmit data and hardware timers to replace software delays. This is the ultimate solution for improving performance.

II. Optimization Methods

2.1 Identify the slowest code

When identifying the slowest code sections, we can usually establish function groups recorded in ticks through the judicious use of timing utime. Code execution time can be measured in ms (milliseconds), us (microseconds), or CPU cycles.

You may add the following @timed_function decorator to time any function or method:

import time

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

Here, we use the mpremote tool to connect to the Raspberry Pi Pico, copy the above code into the REPL, and press Enter to execute (at this point, the decorator has been defined):

How to Speed Up the Operation of MicroPython

Next, define a test function (to simulate time-consuming operations):

# Decorate the test function with the @timed_function decorator
@timed_function
def slow_function():
    for i in range(10000):
        pass
    return "Done"

We paste it into the REPL:

How to Speed Up the Operation of MicroPython

Then call the function and check the timing result:

slow_function()

We can see that the time-consuming result of the function execution has been output:

How to Speed Up the Operation of MicroPython

2.2 Specific Measures for Performance optimization

2.2.1 Performance Bottlenecks and Core Basic Concepts of MicroPython

2.2.1.1 Core Basic Concepts
2.2.1.1.1 Variables and Constants

Here, first we need to understand the difference between variables and constants, which is the foundation of programming; the core difference between the two lies in when their values are determined:

# Variable, stored in a dictionary at runtime
max_count = 10000  
for i in range(max_count):
    # The value of max_count is looked up in the dictionary on every iteration
    pass  
from micropython import const
# Constant, replaced directly with 10000 at compile time
MAX_COUNT = const(10000)  
for i in range(MAX_COUNT):
    # 10000 is used directly in the loop, no dictionary lookup needed
    pass  

2.2.1.1.2 Three Memory Partitions

Embedded microcontrollers (such as the RP2040) have extremely limited memory resources (for example, only 264KB of RAM), and the object storage of MicroPython directly relies on memory partitioning, where heap allocation and deallocation represent the biggest performance bottleneck. We use the metaphor of "Warehouse Management" to understand the three partitions:

Memory RegionAnalogy (Warehouse)Stored ContentCharacteristics (Performance-Related)
Static areaFixed shelves for long-term storage (permanent)Global variables, static variables, program code, constantsNo allocation / reclamation overhead; lifetime matches the program
StackA small shelf for temporary pick-ups (fast)Local variables, function parameters, return addresses of function callsAllocation / release is extremely fast (hardware-level), but space is very small (a few KB)
HeapA miscellaneous area for temporary piles (messy)Dynamically created objects (lists, dicts, byte arrays, class instances)Allocation / reclamation has significant overhead and is prone to fragmentation

For memory management in embedded development, we often face the following several difficulties:

2.2.1.1.3 References and Copies

A reference is essentially the "house number" of an object (analogous to a shortcut on a computer). A variable does not store the data itself, but rather the memory address of the data. Manipulating a reference does not copy the data, so it has extremely low overhead.

# Create a bytearray object on the heap; a stores the object's address (like a house number)
a = bytearray(10)  
# b is a reference to a, pointing to the same object, no new allocation
b = a  
# Operating on b changes the content of a, because they are the same object
b[0] = 1  
# Output: 1
print(a[0])  

In the terminal, the running result is as follows:

How to Speed Up the Operation of MicroPython

Then for copying (here referring to deep copy; we won't go into excessive detail about the difference between shallow copy and deep copy), it will replicate the entire data, create a new object on the heap, and store a new data set, which comes with extremely high overhead (especially for Big data):

# Large bytearray (10KB on the heap)
a = bytearray(10000)  
# Slicing creates a new bytearray (~2KB on the heap), which is a deep copy
b = a[30:2000]  
How to Speed Up the Operation of MicroPython

To avoid excessive heap allocation caused when copying large byte arrays, we can use memoryview, a shallow reference tool provided by MicroPython. Essentially, it acts as a "read/write access pointer" to buffer objects (such as byte arrays, arrays, and bytes). When slicing, it does not copy data but only passes the address, thus completely eliminating heap allocation.

# Large bytearray
a = bytearray(10000)  
# Create a memoryview (allocates only a small object, a few dozen bytes)
mv = memoryview(a)    
# Slice memory view, no new allocation, only passes the address
b = mv[30:2000]       
# Operating on b changes the contents of a, because it is the same data
b[0] = 1           
print(a[30])     

The running results are as follows:

How to Speed Up the Operation of MicroPython

Here, it should be noted that memoryview only supports objects implementing the buffer protocol (bytearray, array, bytes), and does not support lists (lists store object references rather than contiguous data).

After mastering the above basics, you can then understand these advanced concepts of embedded MicroPython:

2.2.1.2 Performance Bottlenecks of MicroPython

The performance bottlenecks of MicroPython mainly stem from three core aspects: the overhead of heap memory allocation and garbage collection (GC), the overhead of interpreted execution of Python bytecode, and inefficient operation/hardware operation methods.

Therefore, we can carry out optimization from the following aspects:

2.2.2 Memory and Object Optimization

The core of this type of optimization is to "avoid dynamically creating objects at runtime and reduce heap allocation as much as possible, thereby lowering the trigger frequency and time consumption of GC", which is the primary step for Performance optimization of embedded MicroPython.

2.2.2.1 Pre-allocated Memory and Fixed Object Size

The object is created only once (e. g., instantiated in the class constructor), and its size is not allowed to grow dynamically (e. g., list append, adding new Attribute–Value Pairs to a dictionary). Especially for buffers (such as buffers for serial communication), pre-allocation and reuse are required.

We can use readinto () instead of read ()(read () allocates a new buffer each time, while readinto () reads data into an existing buffer).

Take the serial port buffer as an example:

from machine import UART, Pin

# 1. Preallocate the buffer (create it only once, avoiding dynamic allocation)
buf = bytearray(64)  # Preallocate a 64-byte buffer

# Initialize UART
uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))

# 2. Use readinto() to read into the preallocated buffer (no new allocation)
while True:
    if uart.any():
        # Data is read into buf, returns the number of bytes read
        n = uart.readinto(buf)  
        # Comparison: uart.read(64) creates a new bytes object each time, triggering heap allocation
        print("recv data:", buf[:n])
2.2.2.2 Use arrays instead of lists + memoryview to avoid data copying

Lists store object references, with non-contiguous memory, and dynamic growth will trigger heap allocation;array module (or bytearray) stores contiguous primitive type data, delivering higher performance after pre-allocation; meanwhile, slice operations (e. g., ba[30:2000]) will create data copies and trigger heap allocation; using memoryview enables direct passing of memory pointers with no copy overhead.

import array
import time

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

# 1. Use array instead of list (stores integers, contiguous memory)
# Preallocate an array of 1000 int elements
arr = array.array('i', [0]*1000)  
# 2. Use memoryview to avoid slice copies
# Large bytearray
ba = bytearray(10000)  

# Direct slicing: creates a copy, triggering a ~2K heap allocation
@timed_function
def func(data):
    pass
    
# Test slice copy (slow and uses memory)
func(ba[30:2000])

# Using memoryview: allocates only a small object, no data copy
mv = memoryview(ba)
# What is passed is a memory pointer, no allocation
func(mv[30:2000])  

The terminal output is as follows:

How to Speed Up the Operation of MicroPython
2.2.2.3 Cached Object Reference

Cache frequently accessed objects (such as self.ba, obj_display.framebuffer) into local variables to avoid attribute lookup on every access — attribute lookup involves dictionary operations, which is time-consuming and may trigger memory allocation.

import time

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

class Foo:
    def __init__(self):
        self.ba = bytearray(100)  
    @timed_function
    def bar(self):
        ba_ref = self.ba
        for i in range(100):
            ba_ref[i] = i % 256
            
class Foo_compare:
    def __init__(self):
        self.ba = bytearray(100)  
    @timed_function
    def bar(self):
        for i in range(100):
            self.ba[i] = i % 256
            
# Test
f = Foo()
f.bar()

f_c = Foo()
f_c.bar()

Click to run, and the terminal outputs the following:

How to Speed Up the Operation of MicroPython
2.2.2.4 Manual Garbage Collection Control

Call gc.collect () manually on a regular basis to trigger GC, so as to prevent GC from being triggered randomly in performance-critical code segments (manual GC allows timing control, and the time cost of frequent minor GCs is far lower than that of a single major GC).

import gc
import time

# Enable GC (enabled by default, can be disabled/enabled manually)
gc.enable()
# Before a performance-critical loop, trigger GC manually
# Clean up memory in advance, takes about 1ms
gc.collect()  

# Performance-critical code section
start = time.ticks_us()
for i in range(10000):
    pass
end = time.ticks_us()

print(f"耗时:{utime.ticks_diff(end, start)/1000}ms")
# Trigger GC periodically in non-critical sections
# gc.collect()

2.2.2 Optimization of Code Execution Efficiency

Such optimizations, built on the basis of memory optimization, further boost the execution speed of code, with optimizations implemented from the bytecode level all the way to the machine code level.

2.2.2.1 Declare constants using const ()

const () replaces identifiers with values (completed at compile time), avoiding runtime dictionary lookups; this delivers remarkable optimization effects, especially for constants used in loops.

from micropython import const
import time

# Declare constants (replaced with values at compile time)
MAX_COUNT = const(100000)
# Binary constants are also supported
PIN_BIT = const(1 << 2)

MAX_COUNT_NOT_USE_CONST = 100000

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

@timed_function
def use_const():
    total = 0
    for i in range(MAX_COUNT):
        total += i
    return total

# Comparison: without const(), every access looks up a dictionary, which takes longer
@timed_function
def no_const():
    global MAX_COUNT_NOT_USE_CONST
    total = 0
    for i in range(MAX_COUNT_NOT_USE_CONST):
        total += i
    return total

result1 = use_const()
result2 = no_const()

The running result in the terminal is as follows:

How to Speed Up the Operation of MicroPython

We can see that the running time of the two is actually almost the same, because in the REPL, the code is executed in an interpreted manner, while const 's real advantage only becomes obvious in pre-compiled bytecode.

2.2.2.2 mpy-cross compile bytecode

Use mpy-cross on a computer to. py scripts to pre-compile them into. mpy bytecode, then upload it to the device.

We can use the pip command to install the mpy-cross tool:

How to Speed Up the Operation of MicroPython

Then, use the following command to MicroPython 's py files compile into mpy files:

How to Speed Up the Operation of MicroPython

We can see that the compiled mpy file is smaller. Next, just use the mpremote tool to deploy it to the device side.

How to Speed Up the Operation of MicroPython
2.2.2.3 Using a Code Transmitter

When MicroPython compiles code, it processes each function individually (classes are functions, as are lambdas and list comprehensions). Functions emerge from the parsing phase and then enter the compiler, which passes the Python function three times:

  1. In the first phase, the compiler collects information about variables and their scopes (local or global), and identifies the emitter type by looking for special types of function decorators;
  2. In the second phase, it calculates the stack usage and code offsets;
  3. In the third phase, codes are transmitted by the required transmitters.

Currently, there are four types of code transmitters:

2.2.2.3.1 native code emitter

The native code emitter takes each bytecode and converts it to equivalent ARM-Thumb machine code. Such functions use the standard C stack to store local variables and directly call C runtime functions.

The native code emitter is invoked via a function decorator:

@micropython.native
def foo(self, arg):
    buf = self.linebuf # Cached object
    # code

The current implementation of the native code emitter has certain limitations:

The tradeoff for improved performance (roughly twice that of bytecode) is an increase in the size of the compile code.

2.2.2.3.2 Viper Code Transmitter

The optimizations discussed above involve standard-compliant Python code. The Viper code emitter is not fully compliant. It supports special Viper native data types in pursuit of performance. Integer processing is non-compliant because it uses machine words: arithmetic on 32-bit hardware is performed modulo 2**32.

The Viper code emitter emits ARM-Thumb machine code for each bytecode and further optimizes certain operations, such as integer arithmetic. For the addition of two integers, the Viper emitter does not call the C runtime function rt_binary_op; instead, it emits the machine instruction "adds" to directly add the two numbers. This is significantly faster than calling rt_binary_op. It is invoked using a decorator:

@micropython.viper
def foo(self, arg: int) -> int:
    # code

Viper supports its own set of types, namely int, uint (unsigned integer), ptr, ptr8, ptr16 and ptr32:

Here, let's test integer accumulation with heavy computational load:

import time
import micropython

def timed_function(name):
    def decorator(f):
        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(name, delta/1000))
            return result
        return new_func
    return decorator
    
# Regular Python function: 1 million accumulations (function name 'normal_add_loop' specified manually)
@timed_function('normal_add_loop')
def normal_add_loop(n: int) -> int:
    total = 0
    for i in range(n):
        total += i * 2 + 5
    return total

# Viper-optimized function: same amount of computation (function name 'viper_add_loop' specified manually)
@timed_function('viper_add_loop')
@micropython.viper
def viper_add_loop(n: int) -> int:
    total = 0
    for i in range(n):
        total += i * 2 + 5
    return total

# Call test (1 million operations, normal timing output)
normal_add_loop(1000000)
viper_add_loop(1000000)

Two functions perform exactly the same 1 million integer operations (i*2+ 5 accumulation), but normal_add_loop is executed purely by interpretation, while viper_add_loop is executed directly as machine code. The terminal output results are as follows:

How to Speed Up the Operation of MicroPython

We conducted tests on the Raspberry Pi Pico, and the time consumption of normal_add_loop is dozens of times that of viper_add_loop.

Viper has two key limitations:

import micropython
# Incorrect example (running in the REPL raises an error: Viper does not support default arguments)
# @micropython.viper
# def viper_default(a: int = 10) -> int:
#     total = 0
#     for i in range(a):
#         total += i
#     return total

# Correct example (no default arguments, 1 million operations, timed)
@micropython.viper
@timed_function
def viper_no_default(a: int) -> int:
    total = 0
    for i in range(a):
        total += i
    return total

# Call test
viper_no_default(1000000)

The running results are as follows:

How to Speed Up the Operation of MicroPython

Let's test the floating-point operations of the function compiled by Viper and ordinary functions again:

import micropython

def timed_function(name):
    def decorator(f):
        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(name, delta/1000))
            return result
        return new_func
    return decorator

# Regular function: 100,000 floating-point multiply-accumulates
@timed_function('normal_float_calc')
def normal_float_calc(n: int) -> float:
    total = 0.0
    for i in range(n):
        total += float(i) * 3.14159
    return total

# Viper function: same 100,000 floating-point operations (no optimization)
@timed_function('viper_float_calc')
@micropython.viper
def viper_float_calc(n: int):
    total = 0.0
    for i in range(n):
        total += float(i) * 3.14159
    return total

# Call test (timing results are almost identical)
normal_float_calc(100000)
viper_float_calc(100000)

The running results are as follows:

How to Speed Up the Operation of MicroPython

Viper's pointer types (ptr8/ptr16/ptr32) are used to directly access contiguous memory (such as bytearray) without boundary checking, and support single-element access via subscript (slicing is not supported). A key optimization technique is: to place the operation of converting an object to a pointer at the beginning of the function rather than inside a loop, as the conversion takes several microseconds, which will be amplified in large loops.

The advantage of pointers is particularly prominent in the scenario of traversing large arrays, which is far faster than array access in ordinary Python.

import micropython

def timed_function(name):
    def decorator(f):
        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(name, delta/1000))
            return result
        return new_func
    return decorator

# Prepare a bytearray of length 10,000 (large array)
ba = bytearray(10000)
for i in range(10000):
    ba[i] = i % 256

# Regular function: iterate over 100,000 bytearray accesses, accumulate values
@timed_function('normal_bytearray_access')
def normal_bytearray_access(ba: bytearray) -> int:
    total = 0
    for i in range(10000):
        total += ba[i]
    return total

# Viper function: access via ptr8 pointer, accumulate values (conversion placed at the start)
@timed_function('viper_ptr8_access')
@micropython.viper
def viper_ptr8_access(ba) -> int:
    buf = ptr8(ba)
    total = 0
    for i in range(10000):
        total += buf[i]
    return total

# Call test (pointer access is much faster than regular access)
normal_bytearray_access(ba)
viper_ptr8_access(ba)

The terminal output is as follows:

How to Speed Up the Operation of MicroPython

viper_ptr8_access takes only one-thirtieth of the time of normal_bytearray_access: the ba[i]in a normal function needs to go through steps such as Python's boundary check and object attribute lookup; Viper's buf[i]directly calculates the memory address and accesses the byte, with no additional overhead.

Next, let's compare the difference between performing pointer operations on the converted object inside a loop and doing so at the beginning:

import micropython

def timed_function(name):
    def decorator(f):
        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(name, delta/1000))
            return result
        return new_func
    return decorator

# Prepare a bytearray of length 10,000 (large array)
ba = bytearray(10000)
for i in range(10000):
    ba[i] = i % 256

# Viper function: repeated ptr8 conversion inside the loop (inefficient)
@timed_function('viper_bad_convert')
@micropython.viper
def viper_bad_convert(ba) -> int:
    total = 0
    for i in range(10000):
        buf = ptr8(ba)
        total += buf[i]
    return total

# Viper function: one-time ptr8 conversion at the start (efficient)
@timed_function('viper_good_convert')
@micropython.viper
def viper_good_convert(ba) -> int:
    buf = ptr8(ba)
    total = 0
    for i in range(10000):
        total += buf[i]
    return total
    
# Call test (the inefficient version takes much longer than the efficient one)
viper_bad_convert(ba)
viper_good_convert(ba)

The running results are as follows:

How to Speed Up the Operation of MicroPython

viper_bad_convert performs a type conversion via ptr8 (ba) in each of 1 million loops (each conversion takes several microseconds, leading to significant accumulated time cost);viper_good_convert only performs the conversion once at the start, thus eliminating redundant overhead.

Viper's integers operate at the machine word level, with arithmetic operations executed modulo 2**32 on 32-bit hardware (truncation occurs upon overflow); this is a trade-off where compatibility is sacrificed for performance, and this characteristic becomes more pronounced under heavy computational loads.

2.2.3 Operation and hardware Optimization

2.2.3.1 Replace floating-point operations with integer operations

Chips without an FPU (floating-point coprocessor) execute floating-point operations extremely slowly, so integer operations are used in performance-critical sections, and conversion to floating-point numbers is only done in non-critical sections.

from machine import ADC, Pin
import array

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

# 1. Pure integer operations: preallocated array + ADC readings (no floating point)
# Preallocate an array of 100 int elements (contiguous memory, no dynamic allocation)
# Pure integer operation: read 16-bit integer ADC values
@timed_function
def adc_read_integer():
    adc_data = array.array('i', [0]*100)
    adc = ADC(Pin(26))
    
    for i in range(100):
        adc_data[i] = adc.read_u16()
    return adc_data

# 2. With floating-point operations: integer readings + floating-point conversion (voltage calculation)
# Step 1: integer readings (same as above)
# Step 2: floating-point operation converts to voltage (reading/65535*3.3)
@timed_function
def adc_read_float():
    adc_data = array.array('i', [0]*100)
    adc = ADC(Pin(26))
  
    for i in range(100):
        adc_data[i] = adc.read_u16()
    
    voltage_data = [x/65535*3.3 for x in adc_data]
    return voltage_data
    
# Run the test, compare elapsed time
print("=== ADC读数性能对比 ===")
integer_data = adc_read_integer()
float_data = adc_read_float()

# Print the first 5 voltage values (verify functionality)
print("\n前5个电压值:", float_data[:5])

Terminal execution:

How to Speed Up the Operation of MicroPython

We can see that floating-point operations take more time than pure integer operations.

2.2.3.2 Direct Register Read/Write

Bypass MicroPython's hardware abstraction layer to directly read and write chip registers, eliminating the overhead of method calls (e. g. fast LED blinking, high-frequency GPIO operations).

from machine import Pin, mem32
import time
from micropython import const

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

# --------------------------
# Configure SIO registers (Raspberry Pi Pico only)
# --------------------------
# SIO module base address (fixed on RP2040)
# SIO GPIO core registers (correct addresses, fixing the earlier error)
SIO_BASE = const(0xD0000000)
# Write all GPIO output values at once
GPIO_OUT = SIO_BASE + 0x010   
# Atomic GPIO set
GPIO_OUT_SET = SIO_BASE + 0x014
# Atomic GPIO clear
GPIO_OUT_CLR = SIO_BASE + 0x018
# Atomic GPIO toggle
GPIO_OUT_XOR = SIO_BASE + 0x01C
# Atomically set GPIO as output mode# Bit mask for GPIO25 (onboard LED) (bit25 corresponds to GPIO25)
GPIO_OE_SET = SIO_BASE + 0x024

# Initialization: set GPIO25 to output mode (run only once, atomic operation)
PIN25_MASK = const(1 << 25)
mem32[GPIO_OE_SET] = PIN25_MASK

# Initialize the Pin object (run only once)
led_pin = Pin(25, Pin.OUT)

# Method 1: operate GPIO25 with regular machine.Pin (hardware abstraction layer, has overhead)
@timed_function
def led_pin_loop(loop_count):
    for _ in range(loop_count):
        led_pin.value(1)
        led_pin.value(0)

# Method 2: operate GPIO25 with SIO registers (no abstraction layer, extremely efficient)
@timed_function
def led_sio_set_clr_loop(loop_count):
    set_reg = GPIO_OUT_SET
    clr_reg = GPIO_OUT_CLR
    mask = PIN25_MASK
    for _ in range(loop_count):
        mem32[set_reg] = mask
        mem32[clr_reg] = mask

# Test running speed
loop_count = 1000

led_pin_loop(loop_count)
led_sio_set_clr_loop(loop_count)

The running results are as follows:

How to Speed Up the Operation of MicroPython
How to Speed Up the Operation of MicroPython

As can be seen, in the SIO loop function, GPIO_OUT_SET, GPIO_OUT_CLR, and PIN25_MASK are cached into local variables, which reduces the overhead of global variable lookup and makes the performance advantage of SIO more prominent.

In scenarios involving arithmetic and hardware data interaction (such as batch ADC data acquisition, high-frequency GPIO signal output, and sensor data stream reading), the CPU often needs to spend a large amount of time performing data transmission operations (such as reading data from peripheral registers to memory and writing arithmetic results to GPIO registers), which preempts the resources required for arithmetic operations.The DMA (Direct Memory Access) controller of the RP2040 can independently complete bulk data transfers between memory and peripherals/registers without CPU intervention, and its core optimization value lies in: freeing the CPU from tedious data transfer tasks and allowing it to focus on core computing logic.

From the perspectives of development and performance, MicroPython only provides relatively basic support for RP2040 DMA, which can only implement simple batch data transmission; in contrast, C language (Pico SDK) allows full configuration of the DMA's transmission mode, trigger conditions and data processing rules. Combined with direct register operations, it can achieve seamless optimization of arithmetic operations and hardware data interaction, making it the optimal choice for high-throughput and low-latency scenarios.

III. Optimization Experiment

3.1 Optimization of LCD Screen

For this, you may refer to:

08 SPI Serial Peripheral Interface - Document Tutorial Draft

For this, you may refer to:

19 DMA Direct Memory Access - Document Tutorial Draft

References

https://docs.micropython.org/en/latest/reference/speed_python.html