cuda简单内积算法

#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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值