模板技巧优化配置 [英] Template trick to optimize out allocations

查看:95
本文介绍了模板技巧优化配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

  struct DoubleVec {
std :: vector< double&数据;
};

DoubleVec operator +(const DoubleVec& lhs,const DoubleVec& rhs){
DoubleVec ans(lhs.size());
for(int i = 0; i ans [i] = lhs [i]] + rhs [i] // assume lhs.size()== rhs.size()
}
return ans;
}

DoubleVec someFunc(DoubleVec a,DoubleVec b,DoubleVec c,DoubleVec d){
DoubleVec ans = a + b + c + d;
}

现在,上面的a + b + c + d将会导致创建3个临时DoubleVec的 - 是有一种方法来优化这个远离与一些类型的模板魔法...即优化到下面的东西:

  DoubleVec ans(a.size()); 
for(int i = 0; i

您可以假设所有DoubleVec都有相同的元素。



高级的想法是在+上做一些类型的模板化魔术,延迟计算直到=,在这一点它看起来自己,只是添加数字,并且合成a [i] + b [i] + c [i] + d [i] ...而不是所有的临时值。



非常感谢!

解决方案

//www.drdobbs.com/184401627\">http://www.drdobbs.com/184401627 或 http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Expression-template )。



这个想法是让 operator + 返回某种代理对象,代表要评估的表达式树。然后写入 operator = 来获取这样的表达式树,并立即评估它,避免创建临时表,并应用任何其他可能适用的优化。 >

I have:

struct DoubleVec {
  std::vector<double> data;
};

DoubleVec operator+(const DoubleVec& lhs, const DoubleVec& rhs) {
  DoubleVec ans(lhs.size());
  for(int i = 0; i < lhs.size(); ++i) {
    ans[i] = lhs[i]] + rhs[i]; // assume lhs.size() == rhs.size()
  }
  return ans;
}

DoubleVec someFunc(DoubleVec a, DoubleVec b, DoubleVec c, DoubleVec d) {
  DoubleVec ans = a + b + c + d;
}

Now, in the above, the "a + b + c + d" will cause the creation of 3 temporary DoubleVec's -- is there a way to optimize this away with some type of template magic ... i.e. to optimize it down to something equivalent to:

DoubleVec ans(a.size());
for(int i = 0; i < ans.size(); i++) ans[i] = a[i] + b[i] + c[i] + d[i];

You can assume all DoubleVec's have the same # of elements.

The high level idea is to have do some type of templateied magic on "+", which "delays the computation" until the =, at which point it looks into itself, goes hmm ... I'm just adding thes numbers, and syntheizes a[i] + b[i] + c[i] + d[i] ... instead of all the temporaries.

Thanks!

解决方案

Yep, that's exactly what expression templates (see http://www.drdobbs.com/184401627 or http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Expression-template for example) are for.

The idea is to make operator+ return some kind of proxy object which represents the expression tree to be evaluated. Then operator= is written to take such an expression tree and evaluate it all at once, avoiding the creation of temporaries, and applying any other optimizations that may be applicable.

这篇关于模板技巧优化配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆