利用模板元編程實現解迴圈最佳化

來源:互聯網
上載者:User

簡介

在《C++ Templates: The Complete Guide》一書中(以下簡稱書),提出了模板元編程最早的實際應用之一:在數值運算中進行解迴圈最佳化。

而本文的標題是噱頭!本文的真正目的是指出這種最佳化措施在增加複雜性的同時,並不一定能明顯改善效率。應當謹慎使用該技術——預設不使用該技術,在點積計算確實是效率瓶頸時考慮採用該技術,並認真測試該技術是否真能提高效率。

背景

數值運算庫中常常需要提供向量點積(dot_product)運算。其定義用C++代碼描述也許更清楚~

template<typename T>
T dot_product(int dim,const T v1[],const T v2[]) {
  T result=0;
  for (int i=0;i<dim;++i)
    result += v1[i]*v2[i];
  return result;
}
我們可以使用這個函數,求2個向量的點積int v1[] = {1,2,3};
int v2[] = {4,5,6};
int r1 = dot_product(3,v1,v2);
得到r1=32

書中指出:“這個結果是正確的,但是在要求高效率的應用中,它耗費了太多的時間”,對於這類特殊的問題,“簡單的把迴圈展開”,如:r1=v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]

“反而會好得多”。

如何便捷的展開迴圈?將每個dot_product(dim,...) 手工重寫成展開式?還是設計一整套函數: dot_product_dim_2,dot_product_dim_3,... ?

無疑這是一個冗長乏味易出錯的方案。

書中提出了一種使用模板元編程解決該問題的方案,讓我們來看看他是怎麼做的。

模板元編程——解迴圈

// 首先是遞迴模板
template<int DIM,typename T>
struct DotProduct {
  static T execute(const T v1[],const T v2[]);
}
template<int DIM,typename T>
T DotProduct<DIM,T>::execute(const T v1[],const T v2[]) {
  return v1[0]*v2[0] + DotProduct<DIM-1,T>::execute(v1+1,v2+1);
}
// 遞迴邊界模板
template<typename T>
struct DotProduct<1,T> {
  static T execute(const T v1[],const T v2[]);
}
template<typename T>
T DotProduct<1,T>::execute(const T v1[],const T v2[]) {
  return v1[0]*v2[0];
}
我們可以使用DotProduct 來進行點積計算了:int v1[] = {1,2,3}; int v2[] = {4,5,6};
int r2 = DotProduct<3,int>::execute(v1,v2);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.