Re: Check if all 256 bits are clear or set ?
skybuck2000 <[email protected]> Thu, 28 Oct 2021 18:02:13 -0700 (PDT)
| Newsgroups | alt.comp.lang.borland-delphi |
|---|---|
| Message-ID | <[email protected]> |
I was just scanning the internet/googling it and I came across this, which is a pretty neat trick to start with lol:
https://github.com/holiman/uint256/blob/master/uint256.go
Particularly this code, written in go, I have never programmed in go but I can still read/understand some of it:
// Cmp compares z and x and returns:
//
// -1 if z < x
// 0 if z == x
// +1 if z > x
//
func (z *Int) Cmp(x *Int) (r int) {
// z < x <=> z - x < 0 i.e. when subtraction overflows.
d0, carry := bits.Sub64(z[0], x[0], 0)
d1, carry := bits.Sub64(z[1], x[1], carry)
d2, carry := bits.Sub64(z[2], x[2], carry)
d3, carry := bits.Sub64(z[3], x[3], carry)
if carry == 1 {
return -1
}
if d0|d1|d2|d3 == 0 {
return 0
}
return 1
}
The interesting part is in:
if d0|d1|d2|d3 == 0 {
Apperently what this code does is it retrieves 4x64 bit quantities.
OR-s them together.
And then checks the result of that with a single branch.
So at the assembler/instruction/compiler generated code level this would probably result in something like:
mov register1, 64 bits from array[0]
mov register2, 64 bits from array[1]
mov register3, 64 bits from array[2]
mov register4, 64 bits from array[3]
or register1, register2
or register1, register3
or register1, register4
jump if zero/jump if not zero.
Something like that, so this could be pretty efficient ! at least "branch times" are avoided/costly comparisons.
The jump zero flag instruction could also be pretty efficient, even more efficient than a cmp, because the or instruction may already have set it.
The only slight downside to this would be 7 extra instructions taking up some instruction cache.
All in all not to bad for a first google ! ;) This might be quite quick actually ! LOL and might be worth it.
And the nicest part about it is it doesn't require any special assembler or avx or mmx or sse instructions... hmmmm...
(And ofcourse the compiler has to be slightly efficient at generating this exact assembler code, but it can probably do that ! ;) maybe it has even some more tricks
up it's sleeve.)
Can you do better than this though ? Wondering...
Bye,
Skybuck.