在網上看到一篇C++模板元編程的文章,裏面提到能夠用來作循環展開,文章地址以下:
https://www.2cto.com/kf/20120...
而後在VS2015裏測了一下,測試代碼以下:html
template <int dim> int get_sum(int* a) { return a[0] + get_sum<dim - 1>(a + 1); } template <> int get_sum<1>(int* a) { return a[0]; } int main() { default_random_engine e; const int n = 1000; int vecs[n]; for (int &v : vecs) { v = e() % 1000; } auto t1 = chrono::high_resolution_clock::now(); int s1 = 0; for (int v : vecs) { s1 += v; } auto t2 = chrono::high_resolution_clock::now(); //int s2 = Sum<n, int>::result(vecs); int s2 = get_sum<n>(vecs); auto t3 = chrono::high_resolution_clock::now(); auto d1 = chrono::duration_cast<chrono::microseconds>(t2 - t1); auto d2 = chrono::duration_cast<chrono::microseconds>(t3 - t2); printf("%d, %d\n", s1, s2); printf("%lld, %lld\n", d1.count(), d2.count()); return 0; }
代碼也挺簡單的,定義一個模板函數來作循環展開。而後比較循環加和展開後加的時間。
選擇64位,開啓O2選項,不展開用時1微秒,展開用時59微秒。
可見作這個展開意義不是特別大。並且當長度變大以後,編譯器處理不了,展開會直接報編譯錯誤。編程