- #include <stdio.h>
- #include <stdlib.h>
- #include <mpi.h>
- #include <math.h>
- //the size of the mandelbrot set
- #define WIDTH 1000
- #define HEIGHT 1000
- //the max number of iterations
- #define MAX_ITERATION 1000
- //the value of the set
- #define MAX_VALUE 4
- int main(int argc, char **argv)
- {
- int rank, size, i, j, k;
- double x, y, x0, y0, x_new, y_new;
- int iterations;
- double start, end;
- int *data;
- MPI_Init(&argc, &argv);
- MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- MPI_Comm_size(MPI_COMM_WORLD, &size);
- start = MPI_Wtime();
- //allocate memory for the data
- data = (int *)malloc(WIDTH * HEIGHT * sizeof(int));
- if (data == NULL)
- {
- printf("Error allocating memoryn");
- MPI_Abort(MPI_COMM_WORLD, 1);
- }
- //calculate the mandelbrot set
- for (i = rank; i < WIDTH; i += size)
- {
- for (j = 0; j < HEIGHT; j++)
- {
- //calculate the initial values
- x = 0;
- y = 0;
- x0 = -2.0 + (4.0 / WIDTH) * i;
- y0 = -2.0 + (4.0 / HEIGHT) * j;
- //iterate until we reach the max number of iterations
- for (iterations = 0; iterations < MAX_ITERATION; iterations++)
- {
- x_new = x * x - y * y + x0;
- y_new = 2 * x * y + y0;
- x = x_new;
- y = y_new;
- if (x * x + y * y > MAX_VALUE)
- break;
- }
- //set the data
- data[i * HEIGHT + j] = iterations;
- }
- }
- //gather the data from all the processes
- MPI_Gather(data, WIDTH * HEIGHT / size, MPI_INT,
- data, WIDTH * HEIGHT / size, MPI_INT,
- 0, MPI_COMM_WORLD);
- end = MPI_Wtime();
- //print the data
- if (rank == 0)
- {
- for (i = 0; i < WIDTH; i++)
- {
- for (j = 0; j < HEIGHT; j++)
- {
- printf("%d ", data[i * HEIGHT + j]);
- }
- printf("n");
- }
- printf("nTime: %fn", end - start);
- }
- //free the memory
- free(data);
- MPI_Finalize();
- return 0;
- }
Parsed in 0.007 seconds