I have a piece of code that demands execution speed over anything else. By using the high_resolution_clock() from std::chrono I found out that this switch() into if-else() ladder is taking over 70% of my execution time. Is there any way to speed this up?
I'm using gcc with -O3 optimization during compiling.
I looked into a similar question: If else ladder optimisation but I can't use a return statement as it would exit the outer loop which I can't.
switch(RPL_OPTION) {
case 0:
for(int k = 0; k < WINDOW_SIZE; k++) {
if(ans[k] >= upper_th) {
//Increasing flag counter
flag_count++;
//Adding the filtered value to the output vector
filtered_output.push_back(ans[k]);
flag_output.push_back(1);
} else if(ans[k] < lower_th) {
//Increasing flag counter
flag_count++;
//Adding the filtered value to the output vector
filtered_output.push_back(ans[k]);
flag_output.push_back(1);
} else {
//Adding the filtered value to the output vector
filtered_output.push_back(ans[k]);
flag_output.push_back(0);
}
}
break;
case 1:
for(int k = 0; k < WINDOW_SIZE; k++) {
if(ans[k] >= upper_th) {
//Increasing flag counter
flag_count++;
//Adding the filtered value to the output vector
filtered_output.push_back(RPL_CONST);
flag_output.push_back(1);
} else if(ans[k] < lower_th) {
//Increasing flag counter
flag_count++;
//Adding the filtered value to the output vector
filtered_output.push_back(RPL_CONST);
flag_output.push_back(1);
} else {
//Adding the filtered value to the output vector
filtered_output.push_back(ans[k]);
flag_output.push_back(0);
}
}
break;
case 2:
for(int k = 0; k < WINDOW_SIZE; k++) {
if(ans[k] >= upper_th) {
//Increasing flag counter
flag_count++;
//Adding the filtered value to the output vector
filtered_output.push_back(upper_th);
flag_output.push_back(1);
} else if(ans[k] < lower_th) {
//Increasing flag counter
flag_count++;
//Adding the filtered value to the output vector
filtered_output.push_back(lower_th);
flag_output.push_back(1);
} else {
//Adding the filtered value to the output vector
filtered_output.push_back(ans[k]);
flag_output.push_back(0);
}
}
break;
case 3:
//Generating a gaussian noise distribution with 0 mean and 1 std deviation
default_random_engine generator(time(0));
normal_distribution<float> dist(0,1);
for(int k = 0; k < WINDOW_SIZE; k++) {
if(ans[k] >= upper_th) {
//Increasing flag counter
flag_count++;
//Calling a random sample from the distribution and calculating a noise value
filtered_output.push_back(dist(generator)*sigma);
flag_output.push_back(1);
continue;
} else if(ans[k] < lower_th) {
//Increasing flag counter
flag_count++;
//Calling a random sample from the distribution and calculating a noise value
filtered_output.push_back(dist(generator)*sigma);
flag_output.push_back(1);
continue;
} else {
//Adding the filtered value to the output vector
filtered_output.push_back(ans[k]);
flag_output.push_back(0);
}
}
break;
}