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.

41 lines
1.1 KiB

21 hours ago
#include <stdio.h>
#include <ctime>
#include <stdlib.h>
#define SIZE 1024
// 基础向量加法函数
void vector_add(float* A, float* B, float* C, int size)
{
for (int i = 0; i < size; ++i)
{
C[i] = A[i] + B[i];
}
}
int main()
{
srand(time(NULL));
// 动态分配内存,并检查是否分配成功
float *A = (float *)malloc(SIZE * sizeof(float));
float *B = (float *)malloc(SIZE * sizeof(float));
float *C = (float *)malloc(SIZE * sizeof(float));
// 随机初始化生成0到99之间的随机浮点数
for (int i = 0; i < SIZE; i++)
{
A[i] = (float)(rand() % 100) / 100.0f;
B[i] = (float)(rand() % 100) / 100.0f;
}
clock_t start = clock();
vector_add(A, B, C, SIZE);
clock_t end = clock();
// 计算并输出向量加法的时间
double time_spent = double(end - start) / CLOCKS_PER_SEC;
printf("使用基础的向量加法:\n当SIZE取%d时初始向量加法时间%lf秒\n", SIZE,time_spent);
// 释放动态分配的内存
free(A);free(B);free(C);
}