lambda tbb并行减少一些参数

时间:2015-07-30 13:41:27

标签: c++ lambda reduce tbb

我想使用tbb parallel reduce来计算方差。 以lambda表达式形式表达以下代码的最佳方法是什么。

感谢。

struct Sum {
    float sum, sum2;
    Sum() : sum(0), sum2(0) {}
    Sum( Sum& s, tbb::split ) {sum = 0; sum2 = 0; }
    void operator()(const tbb::blocked_range<float*>& r ) {
        float temp = sum;
        float temp2 = sum2;
        for( float* a=r.begin(); a!=r.end(); ++a ) {
            temp += *a;
            temp2 += (*a)*(*a);
        }
        sum = temp;
        sum2 = temp2;
    }
    void join( Sum& rhs ) {sum += rhs.sum; sum2 += rhs.sum2; }
    float variance(size_t n){ return (sum2-(sum*sum)/n)/(n - 1); }
};
Sum t;
tbb::parallel_reduce( tbb::blocked_range<float*>( pSrc, pSrc+n ), t );
variance = (t.sum2 - (t.sum * t.sum)/n)/(n - 1);

1 个答案:

答案 0 :(得分:1)

感谢大卫的灵感。这是我的解决方案。

struct Sum {
    float x, x2;
    Sum(float _x, float _x2): x(_x), x2(_x2) {}
    Sum(): x(0), x2(0) {};
};  

Sum sum = tbb::parallel_reduce(tbb::blocked_range<size_t>(0, n), Sum(),
    [&](const tbb::blocked_range<size_t> &r, Sum temp)->Sum{
        for(size_t i=r.begin(); i!=r.end(); ++i){
            temp.x+=pSrc[i];
            temp.x2+=pSrc[i]*pSrc[i];
        }
        return temp;
    },
    [](Sum a, Sum b)->Sum {
        a.x+=b.x;
        a.x2+=b.x2;
        return a;
    });

variance= (sum.x2-(sum.x*sum.x)/n)/(n - 1);