Why is valarray so slow?

后端 未结 7 1987
情书的邮戳
情书的邮戳 2020-12-23 15:18

I am trying to use valarray since it is much like MATLAB while operating vector and matrices. I first did some performance check and found that valarray cannot achieve the p

7条回答
  •  执笔经年
    2020-12-23 15:21

    I finally got this through using delayed evaluation. The code may be ugly since I am just starting learning these C++ advanced concepts.

    Here is the code:

    #include 
    #include 
    #include 
    #include "windows.h"
    
    using namespace std;
    SYSTEMTIME stime;
    LARGE_INTEGER sys_freq;
    
    double gettime_hp();
    
    // To improve the c = a*b (it will generate a temporary first, assigned to 'c' and delete the temporary.
    // Which causes the program really slow
    // The solution is the expression template and let the compiler to decide when all the expression is known.
    
    
    // Delayed evaluation
    //typedef valarray Vector;
    class Vector;
    
    class VecMul
    {
        public:
            const Vector& va;
            const Vector& vb;
            //Vector& vc;
            VecMul(const Vector& v1, const Vector& v2): va(v1), vb(v2) {}
            operator Vector();
    };
    
    class Vector:public valarray
    {
        valarray *p;
    
        public:
            explicit Vector(int n)
            {
                p = new valarray(n);
            }
            Vector& operator = (const VecMul &m)
            {
                for(int i=0; i

    The running result on Visual studio is:

    double operator* 41.2031 ms
    valarray operator* 43.8407 ms
    valarray[i] operator* 42.49 ms
    

提交回复
热议问题