optimize output value using a class and public member

Posted by wiso on Stack Overflow See other posts from Stack Overflow or by wiso
Published on 2010-05-21T15:37:39Z Indexed on 2010/05/21 15:40 UTC
Read the original article Hit count: 212

Filed under:
|
|

Suppose you have a function, and you call it a lot of times, every time the function return a big object. I've optimized the problem using a functor that return void, and store the returning value in a public member:

#include <vector>
const int N = 100;

std::vector<double> fun(const std::vector<double> & v, const int n)
{
    std::vector<double> output = v;
    output[n] *= output[n];
    return output;
}

class F
{
public:
    F() : output(N) {};
    std::vector<double> output;
    void operator()(const std::vector<double> & v, const int n)
    {
        output = v;
        output[n] *= n;
    }
};


int main()
{
    std::vector<double> start(N,10.);
    std::vector<double> end(N);
    double a;

    // first solution
    for (unsigned long int i = 0; i != 10000000; ++i)
      a = fun(start, 2)[3];

    // second solution
    F f;
    for (unsigned long int i = 0; i != 10000000; ++i)
    {
        f(start, 2);
        a = f.output[3];
    }
}

Yes, I can use inline or optimize in an other way this problem, but here I want to stress on this problem: with the functor I declare and construct the output variable output only one time, using the function I do that every time it is called. The second solution is two time faster than the first with g++ -O1 or g++ -O2. What do you think about it, is it an ugly optimization?

© Stack Overflow or respective owner

Related posts about c++

Related posts about optimization