for 指令方法进行求和

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

// for 指令方法进行求和

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

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

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

        #pragma omp for
        for(i = 1; i <= 1000000000; i++) {
            temp += i;
        }
        sumtmp[id] = temp;
    }

    for(long i = 0; i < NUM_THREADS; i++) {
        sum += sumtmp[i];
    }

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

    sum = 0;
    t1 = clock();
    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:30  青衫客36  阅读(382)  评论(0编辑  收藏  举报