Having constructor makes slower calculation

I am very confused with one thing... If I add constructor to struct A then calculating in for loop becomes many times slower. Why? I have no idea.

On my computer times of the snippet in outputs are:

With constructor: 1351

Without constructor: 220

Here is a 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 sin() method from for loop like this:

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];
}

removing constructor does not matter and the time of execution is the same and equals 78.

Do you have similar behaviour with this code? Do you know a reason of this?

EDIT: I compile it with Visual Studio 2013

链接地址: http://www.djcxy.com/p/85718.html

上一篇: 准确的C / C + +时钟在一个多

下一篇: 有构造函数会使计算速度变慢