Add task3_pro.cpp

main
pv3e4i5aj 1 week ago
parent fa45c4f476
commit f0dc849337

@ -0,0 +1,69 @@
#include <stdio.h>
#include <ctime>
#include <stdlib.h>
#define M 1000
#define N 1021
#define Q 1000
//A(M*N),B(N*Q),C(M*Q)对于矩阵维度的说明
void matmul(float** A, float** B, float** C)
{
for (int i = 0; i < M; ++i)
{
for (int j = 0; j < Q; ++j)
{
C[i][j] = 0;
for (int k = 0; k < N; ++k)
{
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
int main()
{
srand(time(NULL));
// 分配矩阵内存
float** A = (float**)malloc(M * sizeof(float*));
float** B = (float**)malloc(N * sizeof(float*));
float** C = (float**)malloc(M * sizeof(float*));
for (int i = 0; i < M; ++i)
{
A[i] = (float*)malloc(N * sizeof(float));
C[i] = (float*)malloc(Q * sizeof(float));
}
for (int i = 0; i < N; ++i)
{
B[i] = (float*)malloc(Q * sizeof(float));
}
// 初始化矩阵数据
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A[i][j] = (float)(rand() % 100) / 100.0f;
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < Q; j++) {
B[i][j] = (float)(rand() % 100) / 100.0f;
}
}
clock_t start = clock();
matmul(A, B, C);
clock_t end = clock();
// 计算并输出向量乘法的时间
double multiply_time_spent = double(end - start) / CLOCKS_PER_SEC;
printf("使用基础的向量乘法:\n当矩阵A的维度为%d*%d,矩阵B的维度为%d*%d时初始向量乘法时间%lf秒\n",M,N,N,Q,multiply_time_spent);
// 释放动态分配的内存
for (int i = 0; i < M; ++i) {
free(A[i]);free(C[i]);
}
for (int i = 0; i < N ;++i) {
free(B[i]);
}
free(A); free(B); free(C);
}
Loading…
Cancel
Save