Effect of integer type in bitwise operations performance

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tassos Souris
    New Member
    • Aug 2008
    • 152

    #1

    Effect of integer type in bitwise operations performance

    hi!

    when using the bitwise operations such as in:

    Code:
    int a = ...;
    int b = ... ;
    
    a & b;
    a | b;
    ...
    does it matter which type we use for performance?? (int vs long vs ..)

    thanks!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Yeah it does. You do not want to use any signed integers like int short or long. Be sure these are all unsigned int, unsigned long, unsigned short.

    The reason is that signed variables can be negative and that means the values could be stored in 2's complement.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      The relative performance of bitwise operators on unsigned int versus unsigned long will typically be different for each compiler implementation.

      An implementation is free to choose any size for unsigned int between that of unsigned short and unsigned long. (Thus, for some implementations there is no practical difference between unsigned int and unsigned long.) Typically, an implementation will use this freedom to select the best size for int; however, there are many dimensions along which to measure relative performance so this choice is necessarily a compromise. I would expect int to in general have the same or higher performance than long, but it could go the other way for any particular operator.

      You could measure the relative performance for your implementation and choose accordingly. However, you need to understand that the results could be quite different when you port your program to a different implementation.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        If you want to optimise for speed and you are using the C99 standard then you could always use one of the types, defined in stdint.h
        Code:
        // unsigned
        uint_fast8_t
        uint_fast16_t
        uint_fast32_t
        uint_fast64_t
        
        //signed
        int_fast8_t
        int_fast16_t
        int_fast32_t
        int_fast64_t
        These are defined by the standard as

        fastest unsigned unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively
        That is a uint_fast8_t might well have 32 bits on a platform that has best performance for integers with 32 bits.

        Comment

        Working...