The presence of a constructor makes a slower calculation

I am very confused by one thing ... If I add a constructor to structure A, then computing in a for loop will be several times slower. What for? I have no idea.

On my computer, the output time of the output fragment:

With constructor: 1351

Without constructor: 220

Here is the code:

#include <iostream>
#include <chrono>
#include <cmath>

using namespace std;
using namespace std::chrono;

const int SIZE = 1024 * 1024 * 32;

using type = int;

struct A {
    type a1[SIZE];
    type a2[SIZE];
    type a3[SIZE];
    type a4[SIZE];
    type a5[SIZE];
    type a6[SIZE];

    A() {} // comment this line and iteration will be twice faster
};

int main() {
    A* a = new A();
    int r;
    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    for (int i = 0; i < SIZE; i++) {
        r = sin(a->a1[i] * a->a2[i] * a->a3[i] * a->a4[i] * a->a5[i] * a->a6[i]);
    }
    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    cout << duration_cast<milliseconds>(t2 - t1).count() << ": " << r << endl;

    delete a;

    system("pause");
    return 0;
}

However, if I remove the sin () method from the for loop as follows:

for (int i = 0; i < SIZE; i++) {
    r = a->a1[i] * a->a2[i] * a->a3[i] * a->a4[i] * a->a5[i] * a->a6[i];
}

deleting the constructor does not matter, and the execution time is the same and equal to 78.

Do you have similar behavior with this code? Do you know the reason for this?

EDIT: I will compile it with Visual Studio 2013

+4
source share

Source: https://habr.com/ru/post/1681439/


All Articles