C++: Set bool value only if not set

后端 未结 6 2170
小鲜肉
小鲜肉 2020-12-17 22:19

I have code in my C++ application that generally does this:

bool myFlag = false;
while (/*some finite condition unrelated to myFlag*/) {
    if (...) {
               


        
相关标签:
6条回答
  • 2020-12-17 22:51

    This question gave me headache too so i simply tested it myself with the following code (C#):

            System.Diagnostics.Stopwatch time = new System.Diagnostics.Stopwatch();
            int i = 0;
            int j = 1;
    
            time.Start();
            if (i != 0)
                i = 0;
            time.Stop();
            Console.WriteLine("compare + set - {0} ticks", time.ElapsedTicks);
    
            time.Reset();
            time.Start();
            if (j != 0)
                j = 0;
            time.Stop();
            Console.WriteLine("compare - {0} ticks", time.ElapsedTicks);
    
    
            time.Reset();
            time.Start();
            i = 0;
            time.Stop();
            Console.WriteLine("set - {0} ticks", time.ElapsedTicks);
    
            Console.ReadLine();
    

    result:

    compare + set - 1 ticks

    compare - 1 ticks

    set - 0 ticks

    while the time, used to set the value surely isn't zero, it shows that even a single query needed more time than just setting the variable.

    0 讨论(0)
  • 2020-12-17 22:53

    You do realize that the check is moot right? If you blindly set it to true and it was not set, you are setting it. If it was already true, then there is no change and you are not setting it, so you effectively can implement it as:

    myFlag = true;
    

    Regarding the potential optimizations, to be able to test, the value must be in the cache, so most of the cost is already paid. On the other hand, the branch (if the compiler does not optimize the if away, which most will) can have a greater impact in performance.

    0 讨论(0)
  • 2020-12-17 22:53

    You are most likely over-thinking the problem as others already mentioned, so let me do the same. The following might be faster if you can afford to double the statements unrelated to myFlag. In fact, you can get rid of myFlag. OK, here we go:

    while (/*some finite condition*/) {
        if (...) {
            // statements
        } else {
            while (/*some finite condition*/) {
                if (...) {
                   // statements, repeated
                }
            }
            // Do something (as if myFlag was true in the OPs example)
            break;
        }
    }
    

    As with all performance optimization: Measure, measure, measure!

    0 讨论(0)
  • 2020-12-17 22:54

    You're almost certainly better off just using myFlag = true;.

    About the best you can hope for from the if (!myFlag) myFlag = true; is that the compiler will notice that the if is irrelevant and optimize it away. In particular, the if statement needs to read the current value of myFlag. If the value isn't already in the cache, that means the instruction will stall while waiting for the data to be read from memory.

    By contrast, if you just write (without testing first) the value can be written to a write queue, and then more instructions can execute immediately. You won't get a stall until/unless you read the value of myFlag (and assuming it's read reasonably soon after writing, it'll probably still be in the cache, so stalling will be minimal).

    0 讨论(0)
  • 2020-12-17 23:00

    It is architecture specific whether if (!myFlag) myFlag = true; will take more time to execute than the simple myFlag = true; even without any optimization. There are architectures (e.g., https://developer.qualcomm.com/hexagon-processor) where both statements will take only one cycle each to execute.

    The only way to figure out on your machine would be by measurement.

    In any case myFlag = true will always be faster or have same execution time as if (!myFlag) myFlag = true;

    0 讨论(0)
  • 2020-12-17 23:05

    CPU-cycle wise, prefer myFlag = true; Think about it: even if the compiler makes no optimization (not really likely), just setting it takes one asm statement, and going through the if takes at least 1 asm statement.

    So just go with the assignment.

    And more importantly, don't try to make hypotheses on such low-level details, specific compiler optimizations can totally go against intuition.

    0 讨论(0)
提交回复
热议问题