Home > Net >  If an array is not read in my code, are the array operations skipped?
If an array is not read in my code, are the array operations skipped?

Time:08-30

I tried benchmarking how fast arrays were compared to vectors. However, I found out that no matter how much I increase the amount it loops, it always ends with 0 nanoseconds or 100 nanoseconds. So I got a little crazy and here's my loop:

#define MAX_VAL 15000
std::chrono::steady_clock::time_point start, end;

    std::cout << "Measuring array...\n";
    start = std::chrono::steady_clock::now();
    for (__int64 a = 0; a < LLONG_MAX; a  )
    {
        for (__int64 b = 0; b < LLONG_MAX; b  )
        {
            for (__int64 c = 0; c < LLONG_MAX; c  )
            {
                for (int i = 1; i < MAX_VAL - 1; i  )
                {
                    arr[i]  = arr[i   1];
                    arr[i - 1] -= arr[i];
                    arr[i] *= 2;
                }
            }
        }
    }
    end = std::chrono::steady_clock::now();

    std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << "\n";

When I printed out the values of the array before the loop, it actually started taking time to do things.

I'm compiling with o2 in release mode. Is this the reason that data not read in the code had its operations skipped?

CodePudding user response:

please take a look at gcc manual to find more about optimization flags in gcc and optimization levels , but to sum up the -O2 optimization will change your code and make a loop optimization in your code , I generated 2 assembly files using GCC , first one is without any optimization and the second is with optimization level set to -O2

with no optimization

take a look at the next assembly part of the file codes and the full file can be found at this link:

     # main.cpp:16:             for (__int64 c = 0; c < LLONG_MAX; c  )
    movl    $0, -48(           
  • Related