Viper bit manipulation challenges #15987
-
My application requires many bit manipulations be performed frequently. Therefore I want my bit manipulation code to be as efficient as possible to allow more time for the processor to perform other tasks. Viper documentation states that Viper is very fast when using pointers. So I tried a simple program to learn bit manipulation with Viper. As you might have guessed, I am having errors related to types, such as: Here I have from array import array
d = array('L',[3])
@micropython.viper
def bit_manip(A:ptr32):
print("A =",f"{A:003b}")
B:int = ((int(A) >> 1 & 1) != 0)
print("B =", f"{B:003b}")
C:int = int(B) | (1 << 1) # why must "B" be converted to an int a second time?
print("C =", f"{C:003b}")
bit_manip(d[0])
# If I do not use int(B) after B:int =, then I receive this error. ViperTypeError: can't do binary op between 'bool' and 'int' The function below used from array import array
d = array('L',[3])
@micropython.viper
def bit_manip(A:ptr32): # I use A:ptr32 with intent of using pointer within the function
print("A =",f"{A:003b}")
B:int = ((A[0] >> 1 & 1) != 0) # the function does not work when I use A[0], but int(A) does work. Why?
print("B =", f"{B:003b}")
C:int = int(B) | (1 << 1)
print("C =", f"{C:003b}")
bit_manip(d[0]) Could you please help me understand how to use Viper bit manipulation with fastest completion time? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
See here for a detailed description of Viper: https://github.com/micropython/micropython/wiki/Improving-performance-with-Viper-code In both examples, you pass
Used with the Viper |
Beta Was this translation helpful? Give feedback.
-
I rewrote four data parsing functions from MicroPython to Viper, which reduced process time from 1100us to 230us. I then rewrote the four Viper functions into one long Viper function, which reduced process time from 230us to 120us. I did not expect one large function to reduce process time by half. Is this a common result? |
Beta Was this translation helpful? Give feedback.
-
Very helpful. I tested my code against this and I agree with your statement. Thank you. |
Beta Was this translation helpful? Give feedback.
See here for a detailed description of Viper: https://github.com/micropython/micropython/wiki/Improving-performance-with-Viper-code
In both examples, you pass
d[0]
tobit_manip
. You need to callbit_manip(d)
, so that within bit_manip, A becomes a pointer to the arrayd
, andA[0]
is the first element ofd
.((A[0] >> 1 & 1) != 0)
yields a boolean because of the != operator.B:int
is then overridden and B winds up as a boolean. That's why you need to cast withint()
again. Note thatB:int
is not a type cast, it's only a type hint. In fact, in viper functions, the only type hints that do something are the type hints of parameters and of the return type.B:int = something
does not influence wh…