builtin µs timing code made platform independent (Python[23] / Pico MicroPython)

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
Posts: 181
Joined: Wed Nov 01, 2017 7:46 am

builtin µs timing code made platform independent (Python[23] / Pico MicroPython)

Post by HermannSW » Wed May 12, 2021 8:23 am

See here for details:
https://www.raspberrypi.org/forums/view ... 8#p1863938

Summary at end:
This is first time that I eliminated platform dependency for using builtin functions from different platforms without performance loss, hopefully this technique will be useful for others as well.

This code runs on Python[23] as well as Pico Micropython, using builtin (fast, single digit µs duration) functions "timeit.default_timer()"/"time.ticks_us()":

Code: Select all

def tst(N, pF=True):
    for n in range(N-9, 1+N):
        print(r if pF else len(str(r)), delta(start,stop), r==r2, delta(stop,stop2))


Pico MicroPython output for Fibonacci numbers F(9991)..F(10000) with more than 2,000(!) decimal digits -- 1.2 seconds for default linear addition algorithm, compared to only 70ms for fast algorithm with only log(n) recursive calls:

Code: Select all

>>> fib.tst(10000,False)                                                                     
2088 1210229 True 69978                                                                      
2088 1221406 True 71887                                                                      
2089 1051971 True 69788                                                                      
2089 1280082 True 75597                                                                      
2089 1102442 True 68994                                                                      
2089 1166174 True 69171                                                                      
2089 1241290 True 70132                                                                      
2090 1076333 True 69608                                                                      
2090 1424052 True 75134                                                                      
2090 978265 True 69157                                                                       

This is how it is done:

Code: Select all

from sys import platform

if platform=='rp2':
    from time import ticks_us as default_timer
    def delta(t0,t1):
        return t1-t0
    from timeit import default_timer
    def delta(t0,t1):
        return int(1000000*(t1-t0)+0.5)
Pico (USB) reboot/reflash tool
https://gist.github.com/Hermann-SW/ca07 ... 6d81de01a7

Pico HTTPS GET through ESP01 serial2wifi

Wireless Pico Micropython REPL

Post Reply