gpt4 book ai didi

c++ - Mandelbrot集的多线程计算

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:57 25 4
gpt4 key购买 nike

我已经创建了一个程序来创建一个 Mandelbrot 集合。现在我正试图让它成为多线程的。

// mandelbrot.cpp
// compile with: g++ -std=c++11 mandelbrot.cpp -o mandelbrot
// view output with: eog mandelbrot.ppm

#include <fstream>
#include <complex> // if you make use of complex number facilities in C++
#include <iostream>
#include <cstdlib>
#include <thread>
#include <mutex>
#include <vector>


using namespace std;

template <class T> struct RGB { T r, g, b; };

template <class T>
class Matrix {
public:
Matrix(const size_t rows, const size_t cols) : _rows(rows), _cols(cols) {
_matrix = new T*[rows];
for (size_t i = 0; i < rows; ++i) {
_matrix[i] = new T[cols];
}
}
Matrix(const Matrix &m) : _rows(m._rows), _cols(m._cols) {
_matrix = new T*[m._rows];
for (size_t i = 0; i < m._rows; ++i) {
_matrix[i] = new T[m._cols];
for (size_t j = 0; j < m._cols; ++j) {
_matrix[i][j] = m._matrix[i][j];
}
}
}
~Matrix() {
for (size_t i = 0; i < _rows; ++i) {
delete [] _matrix[i];
}
delete [] _matrix;
}
T *operator[] (const size_t nIndex)
{
return _matrix[nIndex];
}
size_t width() const { return _cols; }
size_t height() const { return _rows; }
protected:
size_t _rows, _cols;
T **_matrix;
};

// Portable PixMap image
class PPMImage : public Matrix<RGB<unsigned char> >
{
public:
unsigned int size;

PPMImage(const size_t height, const size_t width) : Matrix(height, width) { }
void save(const std::string &filename)
{
std::ofstream out(filename, std::ios_base::binary);
out <<"P6" << std::endl << _cols << " " << _rows << std::endl << 255 << std::endl;
for (size_t y=0; y<_rows; y++)
for (size_t x=0; x<_cols; x++)
out << _matrix[y][x].r << _matrix[y][x].g << _matrix[y][x].b;
}
};

/*Draw mandelbrot according to the provided parameters*/
void draw_Mandelbrot(PPMImage & image, const unsigned width, const unsigned height, double cxmin, double cxmax, double cymin, double cymax,unsigned int max_iterations)
{

for (std::size_t ix = 0; ix < width; ++ix)
for (std::size_t iy = 0; iy < height; ++iy)
{
std::complex<double> c(cxmin + ix / (width - 1.0)*(cxmax - cxmin), cymin + iy / (height - 1.0)*(cymax - cymin));
std::complex<double> z = 0;
unsigned int iterations;

for (iterations = 0; iterations < max_iterations && std::abs(z) < 2.0; ++iterations)
z = z*z + c;

image[iy][ix].r = image[iy][ix].g = image[iy][ix].b = iterations;

}
}

int main()
{
const unsigned width = 1600;
const unsigned height = 1600;

PPMImage image(height, width);


int parts = 8;

std::vector<int>bnd (parts, image.size);

std::thread *tt = new std::thread[parts - 1];

time_t start, end;
time(&start);
//Lauch parts-1 threads
for (int i = 0; i < parts - 1; ++i) {
tt[i] = std::thread(draw_Mandelbrot,ref(image), width, height, -2.0, 0.5, -1.0, 1.0, 10);
}

//Use the main thread to do part of the work !!!
for (int i = parts - 1; i < parts; ++i) {
draw_Mandelbrot(ref(image), width, height, -2.0, 0.5, -1.0, 1.0, 10);
}

//Join parts-1 threads
for (int i = 0; i < parts - 1; ++i)
tt[i].join();

time(&end);
std::cout << difftime(end, start) << " seconds" << std::endl;


image.save("mandelbrot.ppm");

delete[] tt;

return 0;
}

现在每个线程 绘制完整的分形(查看main())。如何让线程绘制分形的不同部分?

最佳答案

你让这(相当多)变得比它需要的更难。这是 OpenMP 几乎完全适合的任务。对于此任务,它以 bare 最少的努力提供了近乎完美的缩放。

我修改了你的 draw_mandelbrot,在外层 for 循环之前插入了一个 pragma:

#pragma omp parallel for
for (int ix = 0; ix < width; ++ix)
for (int iy = 0; iy < height; ++iy)

然后我将你的 main 简化为:

int main() {
const unsigned width = 1600;
const unsigned height = 1600;

PPMImage image(height, width);

clock_t start = clock();
draw_Mandelbrot(image, width, height, -2.0, 0.5, -1.0, 1.0, 10);
clock_t stop = clock();

std::cout << (double(stop - start) / CLOCKS_PER_SEC) << " seconds\n";

image.save("mandelbrot.ppm");

return 0;
}

在我的(相当慢的)机器上,您的原始代码运行了 4.73 秒。我修改后的代码运行时间为 1.38 秒。这是 3.4 倍的代码改进,与普通的单线程版本几乎没有区别。

只是为了它的值(value),我做了更多的重写来得到这个:

// mandelbrot.cpp
// compile with: g++ -std=c++11 mandelbrot.cpp -o mandelbrot
// view output with: eog mandelbrot.ppm

#include <fstream>
#include <complex> // if you make use of complex number facilities in C++
#include <iostream>
#include <cstdlib>
#include <thread>
#include <mutex>
#include <vector>

using namespace std;

template <class T> struct RGB { T r, g, b; };

template <class T>
struct Matrix
{
std::vector<T> data;
size_t rows;
size_t cols;

class proxy {
Matrix &m;
size_t index_1;
public:
proxy(Matrix &m, size_t index_1) : m(m), index_1(index_1) { }

T &operator[](size_t index) { return m.data[index * m.rows + index_1]; }
};

class const_proxy {
Matrix const &m;
size_t index_1;
public:
const_proxy(Matrix const &m, size_t index_1) : m(m), index_1(index_1) { }

T const &operator[](size_t index) const { return m.data[index * m.rows + index_1]; }
};


public:
Matrix(size_t rows, size_t cols) : data(rows * cols), rows(rows), cols(cols) { }

proxy operator[](size_t index) { return proxy(*this, index); }
const_proxy operator[](size_t index) const { return const_proxy(*this, index); }

};

template <class T>
std::ostream &operator<<(std::ostream &out, Matrix<T> const &m) {
out << "P6" << std::endl << m.cols << " " << m.rows << std::endl << 255 << std::endl;
for (size_t y = 0; y < m.rows; y++)
for (size_t x = 0; x < m.cols; x++) {
T pixel = m[y][x];
out << pixel.r << pixel.g << pixel.b;
}
return out;
}

/*Draw Mandelbrot according to the provided parameters*/
template <class T>
void draw_Mandelbrot(T & image, const unsigned width, const unsigned height, double cxmin, double cxmax, double cymin, double cymax, unsigned int max_iterations) {

#pragma omp parallel for
for (int ix = 0; ix < width; ++ix)
for (int iy = 0; iy < height; ++iy)
{
std::complex<double> c(cxmin + ix / (width - 1.0)*(cxmax - cxmin), cymin + iy / (height - 1.0)*(cymax - cymin));
std::complex<double> z = 0;
unsigned int iterations;

for (iterations = 0; iterations < max_iterations && std::abs(z) < 2.0; ++iterations)
z = z*z + c;

image[iy][ix].r = image[iy][ix].g = image[iy][ix].b = iterations;

}
}

int main() {
const unsigned width = 1600;
const unsigned height = 1600;

Matrix<RGB<unsigned char>> image(height, width);

clock_t start = clock();
draw_Mandelbrot(image, width, height, -2.0, 0.5, -1.0, 1.0, 255);
clock_t stop = clock();

std::cout << (double(stop - start) / CLOCKS_PER_SEC) << " seconds\n";

std::ofstream out("mandelbrot.ppm", std::ios::binary);
out << image;

return 0;
}

在我的机器上,这段代码运行大约需要 0.5 到 0.6 秒。

至于为什么我做出这些改变:主要是为了让它更快、更干净、更简单。您的 Matrix 类为每一行(或者可能是列——没有特别注意)分配了一个单独的内存块。这会分配整个矩阵的一个连续 block 。这消除了获取数据的间接级别,并增加了引用的位置,从而提高了缓存使用率。它还减少了使用的数据总量。

从使用 time 更改为使用 clock 进行计时是为了测量 CPU 时间而不是墙上时间(并且通常也会显着提高精度)。

摆脱 PPMImage 类只是因为(IMO)拥有一个派生自 Matrix 类的 PPImage 类没有多大意义(如果有的话)。我想它是可行的(对于“工作”的足够宽松的定义),但它并没有给我留下好的设计印象。如果您坚持要这样做,它至少应该是私有(private)派生,因为您只是将 Matrix 用作实现 PPMImage 类的一种方式,而不是(至少我当然希望不会)尝试对的属性进行断言PPM 图片。

如果出于某种原因,您决定手动处理线程,那么在线程之间划分工作的明显方法仍然是查看 draw_mandelbrot 中的循环。最明显的方法是不理会你的外循环,而是将每次迭代的计算发送到线程池: for (int ix = 0; ix < width;++ix) 计算线程(ix);

compute_thread 的主体基本上是这段代码:

        for (int iy = 0; iy < height; ++iy)
{
std::complex<double> c(cxmin + ix / (width - 1.0)*(cxmax - cxmin), cymin + iy / (height - 1.0)*(cymax - cymin));
std::complex<double> z = 0;
unsigned int iterations;

for (iterations = 0; iterations < max_iterations && std::abs(z) < 2.0; ++iterations)
z = z*z + c;

image[iy][ix].r = image[iy][ix].g = image[iy][ix].b = iterations;

}

将正确的数据传递给计算线程显然会涉及一些工作(每个线程都应该传递对结果图片的一部分的引用),但那将是一个明显且相当干净的划分事物的地方向上。特别是它将工作分成足够多的任务,你可以半自动地获得很好的负载平衡(即,你可以让所有的核心保持忙碌)但又足够大,你不会在通信和同步上浪费大量时间线程。

关于结果,将迭代次数设置为 255,我得到以下结果(缩放到 25%):

enter image description here

...这和我预期的差不多。

关于c++ - Mandelbrot集的多线程计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30070348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com