First time here? Check out the FAQ!

Ask Your Question
0

Modify loop for faster execution

asked Aug 21 '14

Iona gravatar image

updated Aug 23 '14

Hello,

Here's the code which works well for analysis while performing discrete wavelet transform. I've been wondering if this loop could be modified to make the execution faster? Any help would be appreciated.

int rows = signal.size();
int cols = signal[0].size();
int cols_lp1 =(int) ceil( (double) cols / 2);
vector<vector<double> > lp_dn1(rows, vector<double>( cols_lp1));

// Implementing row filtering and column downsampling in each branch.
for (int i =0; i < rows; i++) {
            vector<double> temp_row;
            for (int j=0;j <  cols;j++) {
                    double temp = signal[i][j];
                    temp_row.push_back(temp);
                   }
                    vector<double> oup;
                    branch_lp_dn(name,temp_row,oup);
                    temp_row.clear();

                    for (int j=0;j < (int) oup.size();j++) {
                    lp_dn1[i][j] = oup[j];
                    }
    }
Preview: (hide)

Comments

start with using preallocated vectors/arrays. don't do push_back/clear in inner loops.

(but again, all of it unrelated to opencv..)

berak gravatar imageberak (Aug 22 '14)edit

1 answer

Sort by » oldest newest most voted
0

answered Aug 23 '14

updated Aug 23 '14

Sometimes, you can iterate over every even or odd row/col. This is possible if the accuracy is not a very big deal!

For instance, I would re-write your code to be:

vector <double> temp_row;
double temp;
vector <double> oup;
for (int i = 0; i < rows; i++) { //you can say i +=2 and say the output, if you like it it makes the iteration much faster.
    for (int j = 0; j < cols; j++) {
        temp = signal[i][j];
        temp_row.push_back(temp);
    }
    branch_lp_dn(name, temp_row, oup);
    temp_row.clear();

    for (int j = 0; j < (int) oup.size(); j++) {
        lp_dn1[i][j] = oup[j];
    }
}
Preview: (hide)

Comments

Thanks for your comment. However, initializing temp and oup before the loop is giving run time error. Here's how I modified the code which helped reduction to few msec. Any further ideas would be much appreciated.

vector&lt;double&gt; temp_row;
temp_row.reserve(512);
for (int i =0; i &lt; rows; i++) {
            for (int j=0;j &lt; cols;j++) {
                    double temp = signal[i][j];
                    temp_row.push_back(temp);
                   }
                    vector&lt;double&gt; oup;
                    branch_lp_dn(name,temp_row,oup);
                    temp_row.clear();

                    for (int j=0;j &lt; (int) oup.size();j++) {
                    lp_dn1[i][j] = oup[j];
                    }
    }
Iona gravatar imageIona (Aug 24 '14)edit

Question Tools

Stats

Asked: Aug 21 '14

Seen: 309 times

Last updated: Aug 23 '14