Home > OS >  Why i uses less memory than i while retaining same speed?
Why i uses less memory than i while retaining same speed?

Time:02-24

I was solving George And Accommodation and submitted two accepted versions of code with slight difference. Compiler used: GNU C 14

Version A (Time: 15ms, Memory: 4kb)

    #include <iostream>
    using namespace std;
     
    int main(){
        int n = 0, p = 0, q = 0, a = 0;
        cin >> n;
     
        while(n--){
            cin >> p >> q;
            if(q - p >= 2) a  ;
        }
     
        cout << a;
        
        return 0;
    }

Version B (Time: 15ms, Memory: 8kb)

    #include <iostream>
    using namespace std;
     
    int main(){
        int n = 0, p = 0, q = 0, a = 0;
        cin >> n;
     
        while(n--){
            cin >> p >> q;
            if(q - p >= 2)   a;
        }
     
        cout << a;
        
        return 0;
    }

I always thought a is faster and always use it in my loops. However, why does it require more memory while time being exactly the same? I know the general difference being one increments earlier, and one increments after.

CodePudding user response:

This is just a random effect. It has no meaning.

The memory used is probably measured in pages, so the stack just happened to cross a page boundary in the second case. A page is typically 4kb.

Whether you use a ; or a; is completely irrelevant if a is a built-in type. The compiler will compile it to exactly the same machine instructions. It doesn't matter which of these you use in a loop increment either. Neither is faster than the other or uses more memory than the other.

(Of course this is assuming you enable optimizations. Without optimizations enabled, there might be some weird effects, but measuring speed or memory without enabled optimizations is pointless.)

  •  Tags:  
  • c
  • Related