临界区方法进行求和

// OpenMP4.cpp : 定义控制台应用程序的入口点。

// 临界区方法进行求和

#include "stdafx.h"
#include <time.h>
#include <omp.h>
#include <Windows.h>
#define NUM_THREADS 2

int _tmain(int argc, _TCHAR* argv[])
{
    clock_t t1, t2;
    omp_set_num_threads(NUM_THREADS);
    t1 = clock();
    long long sum = 0;

    #pragma omp parallel
    {
        long id = omp_get_thread_num();
        long i;
        long long sumtmp = 0;

        for(i = id + 1; i <= 1000000000; i = i + NUM_THREADS) {
            sumtmp= sumtmp + i;
        }

        #pragma omp critical
            sum = sum + sumtmp;
    }

    t2 = clock();
    printf("sum = %lld\n", sum);
    printf("parallel time : %d\n", (t2 - t1));

    t1 = clock();
    sum = 0;
    for(long i = 1; i <= 1000000000; i += 1) {
        sum = sum + i;
    }
    t2 = clock();
    printf("sum = %lld\n", sum);
    printf("serial time = %d\n", (t2 - t1));
    system("pause");

    return 0;
}

  

posted @ 2019-05-20 13:32  青衫客36  阅读(162)  评论(0编辑  收藏  举报