Share via


방법: parallel_for_each 루프 작성

이 예제에서는 Concurrency::parallel_for_each 알고리즘을 사용하여 std::array 개체에서 소수 개수를 병렬로 계산하는 방법을 보여 줍니다.

예제

다음 예제에서는 배열에서 소수의 수를 두 번 계산합니다. 이 예제에서는 먼저 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 함수

개념

병렬 알고리즘