Is a bit field any more efficient (computationally) than masking bits and extracting the data by hand?

后端 未结 7 1681
庸人自扰
庸人自扰 2021-02-08 10:16

I have a numerous small pieces of data that I want to be able to shove into one larger data type. Let\'s say that, hypothetically, this is a date and time. The obvious method is

7条回答
  •  一个人的身影
    2021-02-08 10:48

    In this examle I would use the bit field manually.
    But not because of accesses. But because of the ability to compare two dt's.
    In the end the compiler will always generate better code than you (as the compiler will get better over time and never make mistakes) but this code is simple enough that you will probably write optimum code (but this is the kind of micro optimization you should not be worrying about).

    If your dt is an integer formatted as:

    yyyyyyyyyyyy|mmmm|ffffffffd|hhhhh|mmmmmm
    

    Then you can naturally compare them like this.

    dt t1(getTimeStamp());
    dt t2(getTimeStamp());
    
    if (t1 < t2)
    {    std::cout << "T1 happened before T2\n";
    }
    

    By using a bit field structure the code looks like this:

    dt t1(getTimeStamp());
    dt t2(getTimeStamp());
    
    if (convertToInt(t1) < convertToInt(t2))
    {    std::cout << "T1 happened before T2\n";
    }
    // or
    if ((t1.year < t2.year)
        || ((t1.year == t2.year) && ((t1.month < t2.month)
          || ((t1.month == t2.month) && ((t1.day < t2.day)
            || ((t1.day == t2.day) && (t1.hour  etc.....
    

    Of course you could get the best of both worlds by using a union that has the structure on one side and the int as the alternative. Obviously this will depend exactly on how your compiler works and you will need to test that the objects are getting placed in the correct positions (but this would be perfect place to learn about TDD.

提交回复
热议问题