0

No idea about multi-core parallelization. But for simple loops, it might modify little. For the following example, how to make simple loops with multi-core computation in VC++?

#include <iostream>
#include <vector>
#include <ctime>
using namespace std;

void foo(int n, double* a, double* b, double *c, double*d, double* e, double* f, double* g)
{
    for (int i = 0; i < n; ++i)
    {
        a[i] = b[i] * a[i] + c[i] * (d[i] + e[i] + f[i] + g[i]);
    }
}

int main()
{
    int m = 1001001;
    vector<double> a(m), b(m), c(m), d(m), f(m);

    std::clock_t startcputime = std::clock();
    for (int i = 0; i < 1000; ++i)
        foo(1000000, &a[0], &b[0], &c[0], &d[0], &d[1], &f[0], &f[1000]);
    double cpu_duration = (std::clock() - startcputime) / (double)CLOCKS_PER_SEC;
    std::cout << "Finished in " << cpu_duration << " seconds [CPU Clock] " << std::endl;
}
2
  • 2
    OpenMP, OpenCL, OpenACC. Commented Jun 29, 2016 at 13:32
  • I believe that your first step should be to study basics of concurrency and parallelism, so that you have "some idea". Commented Jun 29, 2016 at 13:35

2 Answers 2

5

The concurrency namespace in the Parallel Patterns Library (part of VC++) contains parallel_for which is exactly what you want.

void parallel_foo(int n, double* a, double* b, double *c, double*d, double* e, double* f, double* g)
{
    concurrency::parallel_for(static_cast<size_t>(0), static_cast<size_t>(n), [&](size_t i) {
        a[i] = b[i] * a[i] + c[i] * (d[i] + e[i] + f[i] + g[i]);
    });
}

I'd recommend using size_t for 'n'. This way it gets a little cleaner:

void parallel_foo(size_t n, double* a, double* b, double *c, double*d, double* e, double* f, double* g)
{
    concurrency::parallel_for(0, n, [&](size_t i) {
        a[i] = b[i] * a[i] + c[i] * (d[i] + e[i] + f[i] + g[i]);
    });
}

You should also take a look at the example at msdn

You could use 'amp' as an alternative. Its more powerfull and more complex.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use OpenMP, just add #pragma omp parallel for before for loop.

void foo(int n, double* a, double* b, double *c, double*d, double* e, double* f, double* g)
{
    #pragma omp parallel for
    for (int i = 0; i < n; ++i)
    {
        a[i] = b[i] * a[i] + c[i] * (d[i] + e[i] + f[i] + g[i]);
    }
}

Also, if you using Microsoft Visual studio, you need to enable OpenMP Support in settings

  1. Open the project's Property Pages dialog box.
  2. Expand the Configuration Properties node.
  3. Expand the C/C++ node.
  4. Select the Language property page.
  5. Modify the OpenMP Support property.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.