Share via


方法: combinable を使用して集合を結合する

ここでは、concurrency::combinable クラスを使用して素数の集合を計算する方法について説明します。

次の例では、素数の集合を 2 回計算します。 それぞれの計算結果は、std::bitset オブジェクトに格納されます。 この例ではまず、集合を逐次的に計算した後で、並列処理によっても計算します。 また、それぞれの計算に要する時間もコンソールに出力します。

この例では、concurrency::parallel_for アルゴリズムと combinable オブジェクトを使用して、スレッド ローカルな集合を生成します。 次に、concurrency::combinable::combine_each メソッドを使用して、スレッド ローカルな集合を結合し、最終的な集合として完成させます。

// parallel-combine-primes.cpp
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <bitset>
#include <iostream>

using namespace concurrency;
using namespace std;

// Calls the provided work function and returns the number of milliseconds 
// that it takes to call that function.
template <class Function>
__int64 time_call(Function&& f)
{
   __int64 begin = GetTickCount();
   f();
   return GetTickCount() - begin;
}

// Determines whether the input value is prime.
bool is_prime(int n)
{
   if (n < 2)
      return false;
   for (int i = 2; i < n; ++i)
   {
      if ((n % i) == 0)
         return false;
   }
   return true;
}

const int limit = 40000;

int wmain()
{
   // A set of prime numbers that is computed serially.
   bitset<limit> primes1;

   // A set of prime numbers that is computed in parallel.
   bitset<limit> primes2;

   __int64 elapsed;

   // Compute the set of prime numbers in a serial loop.
   elapsed = time_call([&] 
   {
      for(int i = 0; i < limit; ++i) {
         if (is_prime(i))
            primes1.set(i);
      }
   });
   wcout << L"serial time: " << elapsed << L" ms" << endl << endl;

   // Compute the same set of numbers in parallel.
   elapsed = time_call([&] 
   {
      // Use a parallel_for loop and a combinable object to compute 
      // the set in parallel. 
      // You do not need to synchronize access to the set because the 
      // combinable object provides a separate bitset object to each thread.
      combinable<bitset<limit>> working;
      parallel_for(0, limit, [&](int i) {
         if (is_prime(i))
            working.local().set(i);
      });

      // Merge each thread-local computation into the final result.
      working.combine_each([&](bitset<limit>& local) {
         primes2 |= local;
      });
   });
   wcout << L"parallel time: " << elapsed << L" ms" << endl << endl;
}

4 つのプロセッサを備えたコンピューターを使用したときのサンプル出力を次に示します。

serial time: 312 ms

parallel time: 78 ms

コードのコンパイル

コード例をコピーし、Visual Studio プロジェクトに貼り付けるか、parallel-combine-primes.cpp という名前のファイルに貼り付けてから、Visual Studio のコマンド プロンプト ウィンドウで次のコマンドを実行します。

cl.exe /EHsc parallel-combine-primes.cpp

関連項目

並列コンテナーと並列オブジェクト
combinable クラス
combinable::combine_each メソッド