-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.py
71 lines (58 loc) · 2.08 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# (c) 2023 Hermann Paul von Borries
# MIT License
class MeasureTime:
def __init__(self, title ):
self.title = title
def __enter__( self ):
self.t0 = time.ticks_us()
return self
def __exit__( self, exc_type, exc_val, exc_traceback ):
self.time_usec = time.ticks_diff( time.ticks_us(), self.t0 )
print(f"\tMeasureTime {self.title} {self.time_usec} usec" )
import time
import array
# Original python function
def add_to_array( a, n ):
sum_array = 0
for i in range(len(a)):
a[i] += n
sum_array += a[i]
return sum_array
@micropython.native
def native_add_to_array( a, n ):
sum_array = 0
for i in range(len(a)):
a[i] += n
sum_array += a[i]
return sum_array
@micropython.viper
# The function declaration uses type hints to cast parameters
# and return value to/from viper data types
# pa is a pointer to memory (very fast)
# Since pa does not carry information about the array length,
# a third argument with the length is needed
def viper_add_to_array( pa:ptr32, n:int, length:int)->int:
sum_array = 0
i = 0
while i < length: # while is a bit faster than for...range
# Same instructions now use fast integer arithmetic
pa[i] += n # Pointers are used like arrays
sum_array += pa[i]
i += 1
return sum_array
my_array = array.array("l", (i for i in range(10000)))
with MeasureTime("Plain") as plain:
print(add_to_array( my_array, 10 ))
with MeasureTime("Native") as native:
print(native_add_to_array( my_array, 10 ))
with MeasureTime("Viper") as viper:
print(viper_add_to_array( my_array, 10, len(my_array) ))
print(f"plain/native {plain.time_usec/native.time_usec}")
print(f"plain/viper {plain.time_usec/viper.time_usec}")
@micropython.viper
def myfunction(my_argument):
x:int = 2
x = int(my_argument) + 1 # <- ViperTypeError: local 'x' has type 'int' but source is 'object'
my_float_variable = 1.0
my_float_variable = my_float_variable + float(x) # <-- ViperTypeError: can't do binary op between 'object' and 'int'
myfunction(1)