С помощью профилировщика для исходной программы и каждого способа оптимизации доступа к памяти оценить количество промахов при работе к КЭШ памятью (cache-misses).
#include "lab3.h"
Matrix::Matrix(int size) : size_(size) {
matrix_ = (double**) mm_malloc(size * sizeof(double*), 32);
for (int i = 0; i < size; ++i) {
matrix[i] = (double*)_mm_malloc(size * sizeof(double), 32);
}
}
Matrix::Matrix(const Matrix& other)
: size_(other.size_), matrix_(new double*[other.size_]) {
for (int i = 0; i < size_; ++i) {
matrix_[i] = new double[size_]{};
for (int j = 0; j < size_; ++j) {
matrix_[i][j] = other.matrix_[i][j];
}
}
}
Matrix::~Matrix() {
for (int i = 0; i < size_; ++i) {
mm_free(matrix[i]);
}
mm_free(matrix);
matrix_ = nullptr;
size_ = 0;
}
Matrix& Matrix::operator=(Matrix other) {
std::swap(matrix_, other.matrix_);
std::swap(size_, other.size_);
return *this;
}
void Matrix::Fill() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution ran(0.0, 1.0);
for (int j = 0; j < size_; j++) {
for (int k = 0; k < size_; k++) {
matrix_[j][k] = ran(gen);
}
}
}
int Matrix::GetSize() const { return size_; }
void Matrix::Print() const {
for (int i = 0; i < size_; ++i) {
for (int j = 0; j < size_; ++j) {
std::cout << matrix_[i][j] << " ";
}
std::cout << std::endl;
}
}
void Matrix::DGEMM_BLAS(const Matrix& other) {
if (size_ != other.size_)
throw std::logic_error("Incorrect matrix size for Mul");
Matrix result{size_};
for (int i = 0; i < size_; ++i) {
for (int j = 0; j < size_; ++j) {
result.matrix_[i][j] = 0;
for (int k = 0; k < size_; ++k) {
result.matrix_[i][j] += matrix_[i][k] * other.matrix_[k][j];
}
if (!std::isfinite(result.matrix_[i][j])) {
throw std::runtime_error("Non-finite result encountered");
}
}
}
*this = std::move(result);
}
void Matrix::DGEMM_opt_1(const Matrix& other) {
if (size_ != other.size_)
throw std::logic_error("Размеры матриц должны совпадать для умножения.");
Matrix result(size_);
double temp;
for (int i = 0; i < size_; i++) {
for (int k = 0; k < size_; k++) {
temp = matrix_[i][k];
for (int j = 0; j < size_; j++) {
result.matrix_[i][j] += temp * other.matrix_[k][j];
}
}
}
*this = std::move(result);
}
void Matrix::DGEMM_opt_2(const Matrix& other, int blockSize) {
if (size_ != other.size_)
throw std::logic_error("Размеры матриц должны совпадать для умножения.");
Matrix result(size_);
for (int ii = 0; ii < size_; ii += blockSize) {
for (int jj = 0; jj < size_; jj += blockSize) {
for (int kk = 0; kk < size_; kk += blockSize) {
for (int i = ii; i < std::min(ii + blockSize, size_); ++i) {
for (int k = kk; k < std::min(kk + blockSize, size_); ++k) {
for (int j = jj; j < std::min(jj + blockSize, size_); ++j) {
result.matrix_[i][j] += matrix_[i][k] * other.matrix_[k][j];
}
}
}
}
}
}
*this = std::move(result);
}
void Matrix::DGEMM_opt_3(const Matrix& other) {
if (size_ != other.size_)
throw std::logic_error("Размеры матриц должны совпадать для умножения.");
if (size_ % 4 != 0)
throw std::runtime_error("Размер матрицы должен быть кратен 4 для использования AVX.");
Matrix result(size_);
for (int i = 0; i < size_; i++) {
for (int k = 0; k < size_; k++) {
__m256d temp_v = _mm256_set1_pd(matrix_[i][k]);
for (int j = 0; j < size_; j += 4) {
__m256d b_v = _mm256_load_pd(&other.matrix_[k][j]);
__m256d r_v = _mm256_load_pd(&result.matrix_[i][j]);
__m256d mult_v = _mm256_mul_pd(temp_v, b_v);
r_v = _mm256_add_pd(r_v, mult_v);
_mm256_store_pd(&result.matrix_[i][j], r_v);
}
}
}
*this = std::move(result);
}
void test(int size) {
std::cout << "Классическое умножение" << std::endl;
Matrix A(size), B(size);
A.Fill();
B.Fill();
std::cout << "Матрица A:" << std::endl;
A.Print();
std::cout << "Матрица B:" << std::endl;
B.Print();
auto start = std::chrono::high_resolution_clock::now();
A.DGEMM_BLAS(B);
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = stop - start;
std::cout << "Реузльтат A * B:" << std::endl;
A.Print();
std::cout << "Время умножения: " << duration.count() << " мс" << std::endl;
std::cout << std::endl << "Оптимизированное умножение (построчное)" << std::endl;
A.Fill(); // Перезаполнение матриц для сброса результатов
B.Fill();
std::cout << "Матрица A:" << std::endl;
A.Print();
std::cout << "Матрица B:" << std::endl;
B.Print();
start = std::chrono::high_resolution_clock::now();
A.DGEMM_opt_1(B);
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Реузльтат A * B:" << std::endl;
A.Print();
std::cout << "Оптимизированное умножение 1 (построчный): " << duration.count() << " мс" << std::endl;
std::cout << std::endl << "Оптимизированное умножение (по блокам)" << std::endl;
int blockSize = 16; // Выбор размера блока в зависимости от размера матрицы
std::cout << "Размер блока: " << blockSize << std::endl;
A.Fill();
B.Fill();
std::cout << "Матрица A:" << std::endl;
A.Print();
std::cout << "Матрица B:" << std::endl;
B.Print();
start = std::chrono::high_resolution_clock::now();
A.DGEMM_opt_2(B, blockSize);
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Реузльтат A * B:" << std::endl;
A.Print();
std::cout << "Оптимизированное умножение 2 (блочное): " << duration.count() << " мс" << std::endl;
std::cout << std::endl << "Оптимизированное умножение (векторизация)" << std::endl;
A.Fill();
B.Fill();
std::cout << "Матрица A:" << std::endl;
A.Print();
std::cout << "Матрица B:" << std::endl;
B.Print();
start = std::chrono::high_resolution_clock::now();
A.DGEMM_opt_3(B);
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Реузльтат A * B:" << std::endl;
A.Print();
std::cout << "Оптимизированное умножение 3 (AVX): " << duration.count() << " мс" << std::endl;
}
void func_2() {
std::cout << "Классическое умножение на 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 элементов" << std::endl;
for (int size = 1000; size <= 10000; size+=1000) {
Matrix A(size), B(size);
A.Fill();
B.Fill();
auto start = std::chrono::high_resolution_clock::now();
A.DGEMM_BLAS(B);
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = stop - start;
std::cout << "Время умножения на " << size << " элементов: " << duration.count() << " мс" << std::endl;
}
}
void func_7_1() {
for (int size = 1000; size <= 3000; size+=1000) {
std::cout << "Умножение на " << size << " элементов" << std::endl;
Matrix A(size), B(size);
A.Fill();
B.Fill();
auto start = std::chrono::high_resolution_clock::now();
A.DGEMM_BLAS(B);
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = stop - start;
std::cout << "Время классического умножения: " << duration.count() << " мс" << std::endl;
A.Fill();
B.Fill();
start = std::chrono::high_resolution_clock::now();
A.DGEMM_opt_1(B);
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Время построчного умножения: " << duration.count() << " мс" << std::endl;
A.Fill();
B.Fill();
start = std::chrono::high_resolution_clock::now();
A.DGEMM_opt_2(B, 256);
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Время блочного умножения: " << duration.count() << " мс" << std::endl;
A.Fill();
B.Fill();
start = std::chrono::high_resolution_clock::now();
A.DGEMM_opt_3(B);
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Время векторизованного умножения: " << duration.count() << " мс\n" << std::endl;
}
}
void func_7_2() {
std::cout << "Блочное умножение на 1000 элементов с размерами блоков 4, 8, 16, 32, 64, 128, 256, 512" << std::endl;
int size = 1000;
for (int blocks = 4; blocks <= 512; blocks*=2) {
Matrix A(size), B(size);
A.Fill();
B.Fill();
auto start = std::chrono::high_resolution_clock::now();
A.DGEMM_opt_2(B, blocks);
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = stop - start;
std::cout << "Время блочного умножения с размером " << blocks << " блоков: " << duration.count() << " мс" << std::endl;
}
}
int main(int argc, char* argv[]) {
setlocale(LC_ALL, "Russian");
if (argc != 2) {
std::cerr << "Не задан размер матрицы. Повторите попытку." << std::endl;
return 1;
}
int size = std::atoi(argv[1]);
if (size <= 0) {
std::cerr << "Размер матрицы должен быть положительным." << std::endl;
return 1;
}
test(size);
// func_2();
// func_7_2();
// func_7_1();
return 0;
}