방법: 루프 작성 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;

// Returns the number of milliseconds that it takes to call the passed in function.
template <class Function>
__int64 time_call(Function&& f)
{
    __int64 begin = GetTickCount();
    f();
    return GetTickCount() - begin;
}

// Determines whether the input is a prime.
bool is_prime(int n)
{
    if (n < 2)
    {
        return false;
    }

    for (int i = 2; i < int(std::sqrt(n)) + 1; ++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(begin(a), end(a), [&]
        {
            return n++;
        });

    // Use the for_each algorithm to count, serially, the number
    // of prime numbers in the array.
    LONG prime_count = 0L;
    __int64 elapsed = time_call([&]
        {
            for_each(begin(a), end(a), [&](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, in parallel, the number
    // of prime numbers in the array.
    prime_count = 0L;
    elapsed = time_call([&]
        {
            parallel_for_each(begin(a), end(a), [&](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 125 ms

parallel version:
found 17984 prime numbers
took 63 ms

코드 컴파일

코드를 컴파일하려면 코드를 복사한 다음 Visual Studio 프로젝트에 붙여넣거나 이름이 지정된 parallel-count-primes.cpp 파일에 붙여넣은 다음 Visual Studio 명령 프롬프트 창에서 다음 명령을 실행합니다.

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

강력한 프로그래밍

예제가 알고리즘에 전달하는 parallel_for_each 람다 식은 함수를 사용하여 InterlockedIncrement 루프의 병렬 반복을 사용하여 카운터를 동시에 증가합니다. 공유 리소스에 대한 액세스를 동기화하는 등의 InterlockedIncrement 함수를 사용하는 경우 코드에서 성능 병목 상태를 표시할 수 있습니다. 잠금 없는 동기화 메커니즘(예 concurrency::combinable : 클래스)을 사용하여 공유 리소스에 대한 동시 액세스를 제거할 수 있습니다. 이러한 방식으로 클래스를 combinable 사용하는 예제는 방법: 결합 가능을 사용하여 성능을 향상시키는 방법을 참조하세요.

참고 항목

병렬 알고리즘
parallel_for_each 함수