使用C总结OpenMP [英] Summing with OpenMP using C

查看:329
本文介绍了使用C总结OpenMP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将这段代码并行化大约两天,并不断出现逻辑错误.该程序将使用非常小的dx的总和找到积分的面积,并计算积分的每个离散值.我正在尝试使用openmp实现此功能,但实际上我没有使用openmp的经验.请给我帮助.实际目标是使线程中的suma变量并行化,以便每个线程计算更少的积分值.该程序可以成功编译,但是当我执行该程序时,它将返回错误的结果.

I've been trying to parallelize this piece of code for about two days and keep having logical errors. The program is to find the area of an integral using the sum of the very small dx and calculate each discrete value of the integral. I am trying to implement this with openmp but I actually have no experience with openmp. I would like your help please. The actual goal is to parallelize the suma variable in the threads so every thread calculates less values of the integral. The program compiles successfully but when I execute the program it returns wrong results.

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[]){
    float down = 1, up = 100, dx, suma = 0, j;
    int steps, i, nthreads, tid;
    long starttime, finishtime, runtime; 

    starttime = omp_get_wtime();
    steps = atoi(argv[1]);
    dx = (up - down) / steps;

    nthreads = omp_get_num_threads();
    tid = omp_get_thread_num();
    #pragma omp parallel for private(i, j, tid) reduction(+:suma)
    for(i = 0; i < steps; i++){
        for(j = (steps / nthreads) * tid; j < (steps / nthreads) * (tid + 1); j += dx){
            suma += ((j * j * j) + ((j + dx) * (j + dx) * (j + dx))) / 2 * dx;
        }
    }
    printf("For %d steps the area of the integral  3 * x^2 + 1 from %f to %f is: %f\n", steps, down, up, suma);
    finishtime = omp_get_wtime();
    runtime = finishtime - starttime;
    printf("Runtime: %ld\n", runtime);
    return (0);
}

推荐答案

问题出在您的for循环内.如果您使用for-pragma,则OpenMP会为您执行循环拆分:

The problem lies within your for-loop. If you use the for-pragma, OpenMP does the loop splitting for you:

#pragma omp parallel for private(i) reduction(+:suma)
for(i = 0; i < steps; i++) {
    // recover the x-position of the i-th step
    float x = down + i * dx;
    // evaluate the function at x
    float y = (3.0f * x * x + 1)
    // add the sum of the rectangle to the overall integral
    suma += y * dx
}

即使您要转换为必须自己计算索引的并行化方案,这也是有问题的.外循环应仅执行nthread次.

Even if you would convert to a parallelisation scheme where you would have to compute the indices by yourself, that would be problematic. The outer loop should be executed only nthread times.

您还应该考虑将其切换为双精度以提高准确性.

You should also consider switching to double for increased accuracy.

这篇关于使用C总结OpenMP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆