使用OpenMPI进行内存管理和数据结构

时间:2017-05-22 23:05:11

标签: c++ openmp openmpi

我需要帮助了解如何在代码中更好地管理内存。 sizeof(x)=8(文件main.cpp),这总是等于生成的进程数。我如何确保sizeof(x) = 1并且它是一个大小为num的1D数组(来自main.cpp)。

我想将utils.h导入为静态库导入。我应该如何最好地构建我的代码?如果我指出适当的参考资料以更好地了解使用OpenMPI的ND数组,向量和数据结构,我将非常感激。

我的main.cpp是:

#include <iostream>
#include <utils.h>
#include <mpi.h>

using namespace std;

int main(int argc, const char * argv[]) {


    MPI_Init(NULL, NULL);

    float start = 0., end = 1.;
    int num = 100;

    double *x = linspace(start, end, num);


    for(int i=0;i<num;i++){
        cout << *(x + i) <<endl;
    }


    MPI_Finalize();


    return 0;

}

我的utils.h是:

#ifndef utils_h
#define utils_h


#endif /* utils_h */

#include <iostream>
#include <vector>
#include <cassert>
#include <mpi.h>

using namespace std;


double * linspace(double start_in, double end_in, unsigned long int num_in)
{
    /* This function generates equally spaced elements and returns
    an array with the results */


    int size, rank;

    double start = static_cast<double>(start_in);
    double end = static_cast<double>(end_in);
    unsigned long int num = static_cast<unsigned long int>(num_in);

    double * linspaced;
    linspaced = new double[num];

    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    assert(num!=0);

    if (num == 1)
    {
        *(linspaced) = start_in;
        return linspaced;
    }


    double delta = (end - start) / (num - 1);


    for(int i=rank; i < num - 1; i += size)
    {

        // cout << "i = " << i << endl;
        *( linspaced + i) = start + delta * i;
    }
    linspaced[num-1] = end; // I want to ensure that start and end
    // are exactly the same as the input


    cout << "size-of-linspaced : " << sizeof(linspaced) << endl;
    return linspaced;

}

0 个答案:

没有答案