dimanche 10 novembre 2019

The impact of the class size on performance of the member function

I found that the executation time of member function in class is affected by the class size when traversing an array of objects. I am wondering why this happended and is there any possibility to improve the speed?

The real problem I encountered involved a complex class with multi-level inheritance and virtual function. The different class size (e.g. 5x class size to 2x more time cost) will lead to a remarkable time consumption. A simple test code and the result is shown as follows:

using namespace std;
#include <chrono>
class A{
public:
    char a[5000];
    void Compute(){
        int c = 100;
        c *= 100;
    }
};

class B{
public: 
    char a[1000];
    void Compute(){
        int c = 100;
        c *= 100;
    }
};

void TestClassMemory(){
    int N = 200000;
    A* pA = new A[N];
    B* pB = new B[N];
    int Nloop = 1000;
    std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
    for (int i = 0; i<Nloop; i++){
        for (int j = 0; j<N; j++){
            pA[j].Compute();
        }

    }
    std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
    double dt = std::chrono::duration_cast<std::chrono::duration<double> >(t2 - t1).count();
    std::cout << "A time cost: " << dt;

    t1 = std::chrono::steady_clock::now();
    for (int i = 0; i<Nloop; i++){
        for (int j = 0; j<N; j++){
            pB[j].Compute();
        }
    }
    t2 = std::chrono::steady_clock::now();
    dt = std::chrono::duration_cast<std::chrono::duration<double> >(t2 - t1).count();
    std::cout << "B time cost: " << dt << std::endl;
    std::cout << "size A: " << sizeof(A) << " size B: " << sizeof(B) << std::endl;
    delete [] pA;
    delete [] pB;
}

int main(int argc, char** argv)
{
    TestClassMemory();
}

The expection of the code should have the same time cost while the result shows some unexpectation.

A time cost: 1.28e-07B time cost: 4e-08
size A: 5000 size B: 1000

Aucun commentaire:

Enregistrer un commentaire