Last active
May 5, 2024 12:00
-
-
Save mzaks/6d59ef0dec8aa5ba2d0a5a40128dcafd to your computer and use it in GitHub Desktop.
Branchless comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn compare(s1: DTypePointer[DType.uint8], s2: DTypePointer[DType.uint8], count: Int)->Int: | |
var result = 0 | |
var i = 0 | |
while i < count: | |
var s1i = s1[i] | |
var s2i = s2[i] | |
var smaller = s1i < s2i | |
var bigger = s1i > s2i | |
i += 1 + count * int(smaller or bigger) | |
result = -1 * int(smaller) + 1 * int(bigger) | |
return result | |
def main(): | |
var a = DTypePointer[DType.uint8].alloc(2) | |
var b = DTypePointer[DType.uint8].alloc(2) | |
a[0] = 20 | |
a[1] = 30 | |
b[0] = 20 | |
b[1] = 40 | |
print(compare(a, b, 2)) | |
print(compare(b, a, 2)) | |
print(compare(a, b, 1)) | |
print(compare(b, a, 1)) | |
print(compare(a, a, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment