Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Extra libraries, Code snippets, applications etc. » U++ users applications in progress and useful code snippets, including reference examples! » Optimized bit setting/clearing
Optimized bit setting/clearing [message #54324] Tue, 23 June 2020 10:44
Oblivion is currently offline  Oblivion
Messages: 1092
Registered: August 2007
Senior Contributor
Hi,
I've been testing these bithacks on godbolt.org with various compilers and settings.

It seems that conditional bit setting and clearing can be easily optimized (around ~15% in some cases).

Code:

int flags  = 0;

enum Flags  {
    FLAG_1 = 0x01,
    FLAG_2 = 0x02,
};

void Set1(bool b) { flags = (flags & ~FLAG_1) | (-b & FLAG_1); }

void Set2(bool b) { if(b) flags |= FLAG_2; else flags &= ~FLAG_2; }



Disassembly (CLANG 10.0. Compilation flags: -O3 -ffunction-sections -fdata-sections):
Set1(bool):                               # @Set1(bool)
        mov     eax, dword ptr [rip + flags]
        and     eax, -2
        or      eax, edi
        mov     dword ptr [rip + flags], eax
        ret
Set2(bool):                               # @Set2(bool)
        mov     eax, dword ptr [rip + flags]
        mov     ecx, eax
        and     ecx, -3
        or      eax, 2
        test    edi, edi
        cmove   eax, ecx
        mov     dword ptr [rip + flags], eax
        ret
flags:
        .long   0                       # 0x0



The resulting assembly code is either smaller and faster in most cases on all compilers or it is equal on some.


Best regards,


[Updated on: Tue, 23 June 2020 10:45]

Report message to a moderator

Previous Topic: Simple markdown parser and formatter for RichText
Next Topic: Set text colour in command line
Goto Forum:
  


Current Time: Fri Apr 19 17:14:12 CEST 2024

Total time taken to generate the page: 0.01642 seconds