import time, struct, uctypes
time.sleep(0.1)
SIO_BASE = const(0xd0000000)
DIV_SDIVIDEND = const(0x068 >> 2) # Divider signed dividend
DIV_SDIVISOR = const(0x06c >> 2) # Divider signed divisor
DIV_QUOTIENT = const(0x070 >> 2) # Divider result quotient
t0 = time.ticks_us()
@micropython.viper # Invoke Viper code emitter for this function
def quadratic(z : ptr32):
#zMem = ptr32(z) # Store the memory address of z in zMem as a 'pointer'
for n in range(10000): # Perform the calculation for 10000 values of n
z[n] = (n*(n - 3) + 2)
# Create the bytearray buffer. It will store values as 32-bit integers so 4 bytes per value are needed
z = bytearray(4*10000)
quadratic(z) # Call the Viper function
t1 = time.ticks_us()
print("Viper v1 execution time [us]:",t1-t0)
print(z[:20])
t0 = time.ticks_us()
#z = [n*n - 3*n + 2 for n in range(10000)]
z = [n*(n - 3) + 2 for n in range(10000)]
t1 = time.ticks_us()
print("Normal MicroPython execution time [us]:",t1-t0)
t0 = time.ticks_us()
@micropython.viper # Invoke Viper code emitter for this function
def quadratic1(z : ptr32): # Bytearray, z, is passed as a 'pointer' to the memory address of the bytearray
n = 0
while n < 10000: # Perform the calculation for 10000 values of n
z[n] = (n*(n - 3) + 2)
n += 1
# Create the bytearray buffer. It will store values as
zBuffer1 = bytearray(4*10000) # 32-bit integers so 4 bytes per value are needed
quadratic1(zBuffer1) # Call the Viper function to fill the buffer.
t1 = time.ticks_us()
print("Viper v1 execution time [us]:",t1-t0)
print(zBuffer1[:20])
@micropython.viper
def quad0():
zMem = ptr32(result)
for n in range(10000):
zMem[n] = (n*(n - 3) + 2)
@micropython.viper
def quad():
x = 0
zMem = ptr32(result)
while x < 10000:
zMem[x] = (x*(x - 3) + 2)
x += 1
@micropython.viper
def quad1():
x = 0
z = ptr32(uctypes.addressof(result1))
sio = ptr32(SIO_BASE)
sio[DIV_SDIVISOR] = 7
while x < 10000:
sio[DIV_SDIVIDEND] = (x*(x - 3) + 2)
z[x] = sio[DIV_QUOTIENT]
x += 1
result = bytearray(4*10000)
result1 = bytearray(4*10000)
t0 = time.ticks_us()
quad0()
t1 = time.ticks_us()
print(t1-t0)
print(result[:20])
t0 = time.ticks_us()
quad()
t1 = time.ticks_us()
print(t1-t0)
t0 = time.ticks_us()
quad1()
t1 = time.ticks_us()
print(t1-t0)
print('Compare results:')
print(z[3456],int.from_bytes(result[3456*4:3457*4],'little'),int.from_bytes(result1[3456*4:3457*4],'little'))
resS = uctypes.struct(uctypes.addressof(result),
{'data':(uctypes.ARRAY, 10000 | uctypes.INT32)})
print(resS.data[3456])