You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
#include <iostream>
|
|
|
|
|
#include <ctime> // 用于 clock() 函数
|
|
|
|
|
#include <cstdlib> // 用于 rand() 函数
|
|
|
|
|
#include <cstdio> // 用于 printf 函数
|
|
|
|
|
|
|
|
|
|
// 定义矩阵大小
|
|
|
|
|
#define SIZE 1024
|
|
|
|
|
|
|
|
|
|
// 矩阵乘法函数
|
|
|
|
|
void matmul(float** A, float** B, float** C, int n) {
|
|
|
|
|
// 初始化结果矩阵 C 为 0
|
|
|
|
|
for (int i = 0; i < n; ++i) {
|
|
|
|
|
for (int j = 0; j < n; ++j) {
|
|
|
|
|
C[i][j] = 0;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 矩阵乘法,C[i][j] = A[i][k] * B[k][j] 的累加
|
|
|
|
|
for (int i = 0; i < n; ++i) {
|
|
|
|
|
for (int j = 0; j < n; ++j) {
|
|
|
|
|
for (int k = 0; k < n; ++k) {
|
|
|
|
|
C[i][j] += A[i][k] * B[k][j];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
// 动态分配矩阵内存
|
|
|
|
|
float** A = new float*[SIZE];
|
|
|
|
|
float** B = new float*[SIZE];
|
|
|
|
|
float** C = new float*[SIZE];
|
|
|
|
|
for (int i = 0; i < SIZE; ++i) {
|
|
|
|
|
A[i] = new float[SIZE];
|
|
|
|
|
B[i] = new float[SIZE];
|
|
|
|
|
C[i] = new float[SIZE];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 初始化 A 和 B 矩阵的元素为随机值
|
|
|
|
|
srand(static_cast<unsigned>(time(0))); // 使用时间作为随机种子
|
|
|
|
|
for (int i = 0; i < SIZE; ++i) {
|
|
|
|
|
for (int j = 0; j < SIZE; ++j) {
|
|
|
|
|
A[i][j] = rand() % 100; // 随机数0到99
|
|
|
|
|
B[i][j] = rand() % 100; // 随机数0到99
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 计时开始
|
|
|
|
|
clock_t start = clock();
|
|
|
|
|
|
|
|
|
|
// 执行矩阵乘法
|
|
|
|
|
matmul(A, B, C, SIZE);
|
|
|
|
|
|
|
|
|
|
// 计时结束
|
|
|
|
|
clock_t end = clock();
|
|
|
|
|
|
|
|
|
|
// 计算并输出运行时间
|
|
|
|
|
double elapsed_time = double(end - start) / CLOCKS_PER_SEC;
|
|
|
|
|
printf("矩阵乘法执行时间: %.6f 秒\n", elapsed_time);
|
|
|
|
|
|
|
|
|
|
// 释放动态分配的内存
|
|
|
|
|
for (int i = 0; i < SIZE; ++i) {
|
|
|
|
|
delete[] A[i];
|
|
|
|
|
delete[] B[i];
|
|
|
|
|
delete[] C[i];
|
|
|
|
|
}
|
|
|
|
|
delete[] A;
|
|
|
|
|
delete[] B;
|
|
|
|
|
delete[] C;
|
|
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
|
}
|