東方算程譚

Oriental Code Talk ── επιστημηが与太をこく、弾幕とは無縁のシロモノ。

目次

Blog 利用状況

ニュース

著作とお薦めの品々は

著作とお薦めの品々は
東方熱帯林へ。

あわせて読みたい

わんくま

  1. 東京勉強会#2
    C++/CLI カクテル・レシピ
  2. 東京勉強会#3
    template vs. generics
  3. 大阪勉強会#6
    C++むかしばなし
  4. 東京勉強会#7
    C++むかしばなし
  5. 東京勉強会#8
    STL/CLRによるGeneric Programming
  6. TechEd 2007 @YOKOHAMA
    C++・C++/CLI・C# 適材適所
  7. 東京勉強会#14
    Making of BOF
  8. 東京勉強会#15
    状態遷移
  9. 名古屋勉強会#2
    WinUnit - お気楽お手軽UnitTest

CodeZine

  1. Cで実現する「ぷちオブジェクト指向」
  2. CUnitによるテスト駆動開発
  3. SQLiteで組み込みDB体験(2007年版)
  4. C++/CLIによるCライブラリの.NET化
  5. C# 1.1からC# 3.0まで~言語仕様の進化
  6. BoostでC++0xのライブラリ「TR1」を先取りしよう (1)
  7. BoostでC++0xのライブラリ「TR1」を先取りしよう (2)
  8. BoostでC++0xのライブラリ「TR1」を先取りしよう (3)
  9. BoostでC++0xのライブラリ「TR1」を先取りしよう (4)
  10. BoostでC++0xのライブラリ「TR1」を先取りしよう (5)
  11. C/C++に対応した、もうひとつのUnitTestFramework ─ WinUnit
  12. SQLiteで"おこづかいちょう"
  13. STL/CLRツアーガイド
  14. マージ・ソート : 巨大データのソート法
  15. ヒープソートのアルゴリズム
  16. C++0xの新機能「ラムダ式」を次期Visual Studioでいち早く試す
  17. .NETでマンデルブロ集合を描く
  18. .NETでマンデルブロ集合を描く(後日談)
  19. C++/CLI : とある文字列の相互変換(コンバージョン)
  20. インテルTBBによる選択ソートの高速化
  21. インテルTBB3.0 によるパイプライン処理
  22. Visual C++ 2010に追加されたSTLアルゴリズム
  23. Visual C++ 2010に追加されたSTLコンテナ「forward_list」
  24. shared_ptrによるObserverパターンの実装
  25. .NETでマンデルブロ集合を描く(番外編) ── OpenCLで超並列コンピューティング
  26. StateパターンでCSVを読む
  27. 状態遷移表からStateパターンを自動生成する
  28. 「ソートも、サーチも、あるんだよ」~標準C++ライブラリにみるアルゴリズムの面白さ
  29. インテルTBBの同期メカニズム
  30. なぜsetを使っちゃいけないの?
  31. WPFアプリケーションで腕試し ~C++でもWPFアプリを
  32. C++11 : スレッド・ライブラリひとめぐり
  33. Google製のC++ Unit Test Framework「Google Test」を使ってみる
  34. メールでデータベースを更新するココロミ
  35. Visitorパターンで遊んでみたよ
  36. Collection 2題:「WPFにバインドできる辞書」と「重複を許す検索set」
  37. Visual C++ 2012:stateless-lambdaとSQLiteのぷち拡張
  38. 「Visual C++ Compiler November 2012 CTP」で追加された6つの新機能

@IT

  1. Vista時代のVisual C++の流儀(前編)Vista到来。既存C/C++資産の.NET化を始めよう!
  2. Vista時代のVisual C++の流儀(中編)MFCから.NETへの実践的移行計画
  3. Vista時代のVisual C++の流儀(後編) STL/CLRによるDocument/Viewアーキテクチャ
  4. C++開発者のための単体テスト入門 第1回 C++開発者の皆さん。テスト、ちゃんとしていますか?
  5. C++開発者のための単体テスト入門 第2回 C++アプリケーションの効率的なテスト手法(CppUnit編)
  6. C++開発者のための単体テスト入門 第3回 C++アプリケーションの効率的なテスト手法(NUnit編)

AWARDS


Microsoft MVP
for Visual Developer - Visual C++


Wankuma MVP
for いぢわる C++


Nyantora MVP
for こくまろ中国茶

Xbox

Links

記事カテゴリ

書庫

日記カテゴリ

2010年8月6日 #

TBBで遊んでみたよ(15)

TBBの並列アルゴリズム parallel_なんちゃら の中から使用頻度の高そげなparallel_reduce をご紹介。

 

まぁキホン parallel_for と同じく繰り返し(loop)の並列化なんだけども parallel_reduce には繰り返しの合間に reduction(リダクション:還元/縮約/要は"おまとめ")が割り込みます。

 

ふたつのベクトル x[0..N-1] y[0..N-1] の内積を求めてみんとす。内積ちゅーの:


 
x
y = x[i]*y[i] (i = 0..N-1)


ですな。こいつはインデクスを 0..M-1 M..N-1 の二つに分けて


 
x[i]*y[i] (i = 0..M-1)

 x[i]*y[i] (i = M..N-1) との


和を求めても同じ結果。いくつに分割してもかまわんから並列処理にはうってつけ。

ただし、それぞれの部分和を積算(おまとめ)するとこ(ココがreduction)では各スレッドが勝手にやらんようにガードせんならんです。

 

parallel_reduceにはloop範囲と初期値、処理本体およびreduction処理を与えます。

 

#include <iostream>
#include <array>
#include <numeric>
#include <tbb/tbb.h>

using namespace std;


// 作為的に遅い掛け算
double mult(double x, double y) {
  const int N = 100000;
  double sum = 0.0;
  for ( int i = 0; i < N; ++i ) {
    sum += x*y;
  }
  return sum / (double)N;
};


// フツーに内積
tbb::tick_count::interval_t
serial_inner_product(double x[], double y[], double& z, int n) {
  tbb::tick_count t = tbb::tick_count::now();
  double result = 0.0;
  for ( int i = 0; i < n; ++i ) {
    result += mult(*x,*y);
    ++x; ++y;
  }
  z = result;
  return tbb::tick_count::now() - t;
}


// 並列に内積
tbb::tick_count::interval_t
parallel_inner_product(double x[], double y[], double& z, int n) {
  tbb::tick_count t = tbb::tick_count::now();
  z = tbb::parallel_reduce( tbb::blocked_range<int>(0,n), 0.0, // [0,n) の範囲で、初期値0.0
       // 切り分けられた範囲での内積を求め
       [&](const tbb::blocked_range<int>& range, const double& value) -> double {
         double result = value;
         for ( int i = range.begin(); i != range.end(); ++i ) {
           result += mult(x[i],y[i]);
         }
         return result;
       },
       // リダクション汁
       [](const double& x, const double& y) { return x + y; });
  return tbb::tick_count::now() - t;
}

int main() {
  // 1*1 + 2*2 + 3*3 + ... + N*N を求めるよ
  const int N = 100;
  array<double,N> x;
  array<double,N> y;
  iota(x.begin(),x.end(),1.0);
  iota(y.begin(),y.end(),1.0);
  double sz, pz;
  std::cout << "serial:   " << serial_inner_product(&x[0],&y[0],sz,N).seconds() << "[sec.]\n";
  std::cout << "parallel: " << parallel_inner_product(&x[0],&y[0],pz,N).seconds() << "[sec.]\n";
  std::cout << sz << '/' << pz << std::endl;
 
}
 
 

実行結果(dual-core)

serial:   0.0807083[sec.]

parallel: 0.0465302[sec.]

338350/338350

 

おー、いぃ感じにcore数なりのスピードアップなりねー

posted @ 20:14 | Feedback (1)

右辺地産地消(違)のサンプル

R-value reference  のつづき。

 

先だってのエントリ、正確さに欠ける言い回しがあったかな。

R-value reference / move semantics は、右辺値からそのナカミをmoveする機能じゃありません。

右辺値であればそれは一時オブジェクトであり、いずれ捨てられる運命。

ならば右辺値からナカミをひっぺがして使える。

そのためには、もらった引数が右辺値であることが識別できるからくりが言語レベルで必要。

右辺値を T&& にmatchさせて関数を呼び分けてあげよう。

ってゆースンポーです。実際にナカミをひっぺがすのはプログラマのお仕事。言語サイドではナカミをひっぺがす、つまり移動(move)可能ってゆー意味(semantics)を伴って呼び出されたことをプログラマに教えてあげるカラクリを用意してくれた。ってーのが右辺値参照の意味となりますか。

んでもって右辺値参照のサンプル、ショボい文字列 shobostr をこしらえてみんとす。

 
#include <iostream> // cout,err
#include <utility>  // move
#include <cstring>  // strほげほげ()

using namespace std;


// ショボい文字列
class shobostr {
private:
  char* body;
public:
  // デフォルト コンストラクタ
  shobostr() : body(nullptr) { cerr << "ctor()\n"; }
  // C文字列を食うコンストラクタ
  shobostr(const char* cstr) {
    cerr << "ctor(const char*)\n";
    body = new char[strlen(cstr)+1];
    strcpy(body,cstr);
  }
  // コピー コンストラクタ
  shobostr(const shobostr& ss) {
    cerr << "ctor(const shobostr&)\n";
    body = new char[strlen(ss.body)+1];
    strcpy(body,ss.body);
  }
#ifdef RVR
  // 右辺値参照 コンストラクタ
  shobostr(shobostr&& rvr) {
    cerr << "ctor(shobostr&&)\n";
    body = rvr.body; // 引数から引き剥がすよ
    rvr.body = nullptr;
  }
#endif
  // デストラクタ
  ~shobostr() {
    cerr << "dtor() for " << (body ? body : "(null)") << '\n';
    delete[] body;
  }
  // C文字列を代入
  shobostr& operator=(const char* cstr) {
    cerr << "operator=(const char*)\n";
    delete[] body;
    body = new char[strlen(cstr)+1];
    strcpy(body,cstr);
    return *this;
  }
  // コピー
  shobostr& operator=(const shobostr& ss) {
    cerr << "operator=(const shobostr&)\n";
    if ( &ss != this ) {
      delete[] body;
      body = new char[strlen(ss.body)+1];
      strcpy(body,ss.body);
    }
    return *this;
  }
#ifdef RVR
  // 右辺値参照 コピー
  shobostr& operator=(shobostr&& rvr) {
    cerr << "operator=(const shobostr&)\n";
    if ( &rvr != this ) {
      delete[] body;
      body = rvr.body; // 右辺から引き剥がすよ
      rvr.body = nullptr;
    }
    return *this;
  }
#endif
  // 連結
  friend shobostr operator+(const shobostr& lhs, const shobostr& rhs) {
    cerr << "operator+(const shobostr&,const shobostr&)\n";
    shobostr result;
    result.body = new char[strlen(lhs.body)+strlen(rhs.body)+1];
    strcpy(result.body, lhs.body);
    strcat(result.body, rhs.body);
    return result;
  }
};


// こっからおためし
int main() {
  shobostr s0("Hello,");
  shobostr s1("world");
  shobostr s2(s0+s1);
}

 

実行結果:

--- RVR disabled ---

ctor(const char*)

ctor(const char*)

operator+(const shobostr&,const shobostr&)

ctor()

ctor(const shobostr&) s2:コピーコンストラクタ

dtor() for Hello,world +の結果を捨ててるMOTTAINAIトコ

dtor() for Hello,world

dtor() for world

dtor() for Hello,

 

--- RVR enabled ---

ctor(const char*)

ctor(const char*)

operator+(const shobostr&,const shobostr&)

ctor()

ctor(shobostr&&) s2: 右辺値参照版 コピーコンストラクタ

dtor() for (null) operator+の戻り値からbodyが移動してゆー

dtor() for Hello,world

dtor() for world

dtor() for Hello,

 

posted @ 20:07 | Feedback (25)