次の方法で共有


方法: parallel_for_each ループを記述する

この例では、Concurrency::parallel_for_each アルゴリズムを使用して、std::array オブジェクトの素数の数を並列に計算する方法について説明します。

使用例

次の例では、配列に含まれる素数の数を 2 回計算します。 最初に、std::for_each アルゴリズムを使用して、逐次的に数を計算します。 次に、parallel_for_each アルゴリズムを使用して、同じタスクを並列に実行します。 また、それぞれの計算に要する時間もコンソールに出力します。

// parallel-count-primes.cpp
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <iostream>
#include <algorithm>
#include <array>

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;
}

int wmain()
{
   // Create an array object that contains 200000 integers.
   array<int, 200000> a;

   // Initialize the array such that a[i] == i.
   int n = 0;
   generate(a.begin(), a.end(), [&] {
      return n++;
   });

   LONG prime_count;
   __int64 elapsed;

   // Use the for_each algorithm to count the number of prime numbers
   // in the array serially.
   prime_count = 0L;
   elapsed = time_call([&] {
      for_each (a.begin(), a.end(), [&](int n ) { 
         if (is_prime(n))
            ++prime_count;
      });
   });
   wcout << L"serial version: " << endl
         << L"found " << prime_count << L" prime numbers" << endl
         << L"took " << elapsed << L" ms" << endl << endl;

   // Use the parallel_for_each algorithm to count the number of prime numbers
   // in the array in parallel.
   prime_count = 0L;
   elapsed = time_call([&] {
      parallel_for_each (a.begin(), a.end(), [&](int n ) { 
         if (is_prime(n))
            InterlockedIncrement(&prime_count);
      });
   });
   wcout << L"parallel version: " << endl
         << L"found " << prime_count << L" prime numbers" << endl
         << L"took " << elapsed << L" ms" << endl << endl;
}

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

serial version:
found 17984 prime numbers
took 6115 ms

parallel version:
found 17984 prime numbers
took 1653 ms

コードのコンパイル

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

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

信頼性の高いプログラミング

この例で parallel_for_each アルゴリズムに渡すラムダ式では、InterlockedIncrement 関数を使用して、ループの反復処理を並列で行い、カウンターを同時にインクリメントします。 InterlockedIncrement などの関数を使用して共有リソースへのアクセスを同期化すると、コードのパフォーマンスのボトルネックを示すことができます。 Concurrency::combinable クラスなどのロック制御不要の同期機構を使用して、共有リソースへの同時アクセスをなくすことができます。 combinable クラスのこのような使用例については、「方法: combinable を使用してパフォーマンスを向上させる」を参照してください。

参照

参照

parallel_for_each 関数

概念

並列アルゴリズム