Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Fri Mar 15 00:00:01 UTC 2024


On 15/03/2024 12:47 PM, Basile B. wrote:
> On Thursday, 14 March 2024 at 23:39:33 UTC, Liam McGillivray wrote:
>> On Thursday, 14 March 2024 at 01:58:46 UTC, Richard (Rikki) Andrew 
>> Cattermole wrote:
>>> [...]
>>
>> I tried to rework the functions to use bitwise operations, but it was 
>> difficult to figure out the correct logic. I decided that it's not 
>> worth the hassle, so I just changed the value storage from `bool[3]` 
>> to `ubyte`. Now it works much more like your version.
>> https://github.com/LiamM32/Open_Emblem/blob/c2014ab3f77e89c0cedcd6dbf7f8362ebfac33a9/source/common.d
>>
>> I did a little reading, so now I understand what it means when you 
>> have `&= 7`. But I want to ask, is this faster than `%= 8`? If not, I 
>> would like to change it to the latter for readability.
> 
> `%=8` will be codegened using slower intructions w/o optimz enabled but 
> with `&=7` you directly get the right instruction, which does not 
> involves integer division. See https://godbolt.org/z/74vbba5aG

Yes, it'll depend upon how smart the compiler is at optimizing and it 
may not occur in non-optimizing builds.

The modulas instructions are based upon division, this is an incredibly 
expensive operation.

https://stackoverflow.com/a/8022107

The division instruction on Haswell for integers ranges from 9 cycles 
for 8bit, all the way up to 36 cycles for 64bit.


More information about the Digitalmars-d-learn mailing list