-
February 19th, 2011, 12:11 PM
#1
logging inside loop
Hi,
I have this function to calculate the standard deviation, I need to output (logging) intermediate values inside the for loop if the variable log is true, otherwise if log is false, i will output nothing. However, I cannot use if(log == true) inside the loop, and I cannot duplicate the code for when (log == false).
I'd appreciatte some help. Thanks
Code:
double StdDev(const std::vector<double> &input, bool log){
int elements = input.size();
double sum = 0;
double sumsq = 0;
for(int i = 0; i < elements; ++i) {
sum += input[i];
sumsq += input[i]*input[i];
}
double mean = sum/elements;
double variance = sumsq / elements - mean*mean;
return sqrt(variance);
}
Last edited by acosgaya; February 19th, 2011 at 01:21 PM.
-
February 19th, 2011, 12:55 PM
#2
Re: logging inside loop
hmm... one idea that pops into my mind is something like this:
Code:
template<bool log>
double StdDev(const std::vector<double> &input){
int elements = input.size();
double sum = 0;
double sumsq = 0;
for(int i = 0; i < elements; ++i) {
sum += input[i];
sumsq += input[i]*input[i];
if(log) {
// ...
}
}
double mean = sum/elements;
double variance = sumsq / elements - mean*mean;
return sqrt(variance);
}
double StdDev(const std::vector<double> &input, bool log){
return log ? StdDev<true>(input) : StdDev<false>(input);
}
The idea being that a compiler should be able to optimise out the check for log in the function template since the value of log is known at compile time. Personally, if the logging only happens in the loop body, and given that the loop is pretty small and not too complicated, I would just duplicate the loop. Or, it may turn out that just checking for log in the loop isn't so bad after all.
-
February 19th, 2011, 01:44 PM
#3
Re: logging inside loop
Thanks for the comments,
I'm not sure I got your ideas right, however, I cannot pay the cost of an "if(log)" condition inside a loop, and I cannot duplicate code.
-
February 19th, 2011, 01:50 PM
#4
Re: logging inside loop
Originally Posted by acxx78
Thanks for the comments,
I'm not sure I got your ideas right, however, I cannot pay the cost of an "if(log)" condition inside a loop, and I cannot duplicate code.
The point is there will be no cost for the if (log) part, as long as you are using a decent compiler that will optimize the jump away (assuming an optimized release built). The templates are instantiated at compile-time.
Last edited by ltcmelo; February 19th, 2011 at 01:53 PM.
-
February 19th, 2011, 02:07 PM
#5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|