#include<cuda_runtime_api.h>
#include<cuda_runtime.h>
#include<device_launch_parameters.h>
#include<iostream>
#include<Windows.h>
#include<time.h>
#include<math.h>
#include<device_functions.h>
using namespace std;
__global__ void jia(int* a, int* b, int* c) {
__shared__ int sdata[100];
int idx = threadIdx.x;
int x = blockIdx.x * blockDim.x + threadIdx.x * 2;
sdata[idx] = a[idx] * c[idx];
__syncthreads();
if (idx < 64)sdata[idx] += sdata[idx + 64];
__syncthreads();
if (idx < 32) {
sdata[idx] += sdata[idx + 32];
sdata[idx] += sdata[idx + 16];
sdata[idx] += sdata[idx + 8];
sdata[idx] += sdata[idx + 4];
sdata[idx] += sdata[idx + 2];
sdata[idx] += sdata[idx + 1];
}
if (idx == 0)b[0] = sdata[0];
}
int main() {
int ha[128] = { 0 };
int* da, * db, * dc;
int hb[128], hc[128] = { 2 };
for (int i = 0; i < 100; i++) {
ha[i] = i + 1;
hc[i] = 2;
}
cudaMalloc((void**)&da, sizeof(int) * 128);
cudaMalloc((void**)&db, sizeof(int) * 128);
cudaMalloc((void**)&dc, sizeof(int) * 128);
clock_t t1 = clock();
cudaMemcpy(da, ha, sizeof(int) * 128, cudaMemcpyHostToDevice);
cudaMemcpy(dc, hc, sizeof(int) * 128, cudaMemcpyHostToDevice);
dim3 Block(128);
jia << <1, Block >> > (da, db, dc);
cudaMemcpy(hb, db, sizeof(int), cudaMemcpyDeviceToHost);
clock_t t2 = clock();
cout << hb[0] << endl;
cout << t2 - t1 << endl;
cudaFree(da);
cudaFree(db);
}
cuda简单内积算法
最新推荐文章于 2024-06-12 01:15:34 发布