分享方式:


如何:撰寫 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;
}

下列範例輸出適用于具有四個核心的電腦。

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 演算法的 Lambda 運算式會使用 函 InterlockedIncrement 式來啟用迴圈的平行反覆運算,以同時遞增計數器。 如果您使用 之類的 InterlockedIncrement 函式來同步存取共用資源,您可以在程式碼中呈現效能瓶頸。 您可以使用無鎖定同步處理機制,例如 類別 concurrency::combinable ,來消除對共用資源的同時存取。 如需以這種方式使用 combinable 類別的範例,請參閱 如何:使用可組合來改善效能

另請參閱

平行演算法
parallel_for_each 功能