测试在kernel里面交换全局内存的值

本文通过CUDA内核实现了一个全局内存交换算法,并在GPU上进行了性能测试,对比了GPU与CPU在相同任务上的运行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

///****测试在kernel里面交换全局内存的值
#include<iostream>
#include<cuda.h>
#include<cuda_runtime.h>
#include<time.h>
using namespace std;
const int N=10000;


__global__ void change(int *a,int *b)
{
int temp;
for(int i=0;i<N;i++)
{
/*temp=a[i];
a[i]=b[i];
b[i]=a[i];*/
temp=a[i]+b[i];
}
}
int main(void)
{
int ha[N],hb[N];
int *da,*db;
clock_t h_start,h_elapsed;
cudaMalloc((void**)&da,N*sizeof(int));
cudaMalloc((void**)&db,N*sizeof(int));
for(int i=0;i<N;i++)
{
ha[i]=i;
hb[i]=2*i;
}
cudaMemcpy(da,ha,N*sizeof(int),cudaMemcpyHostToDevice);
cudaMemcpy(db,hb,N*sizeof(int),cudaMemcpyHostToDevice);
cudaEvent_t start,stop;
float elapsed;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start,0);
for(int i=0;i<1000;i++)
{change<<<1,1>>>(da,db);}
cudaDeviceSynchronize();


cudaEventRecord(stop,0);
cudaEventSynchronize(stop);
cudaEventElapsedTime(&elapsed,start,stop);
cout<<"gpu__"<<elapsed<<endl;


cudaMemcpy(ha,da,N*sizeof(int),cudaMemcpyDeviceToHost);
cudaMemcpy(hb,db,N*sizeof(int),cudaMemcpyDeviceToHost);
/*for(int i=0;i<N;i++)
{
cout<<ha[i]<<"  "<<hb[i]<<endl;
}*/
h_start=clock();
int temp;
for(int j=0;j<1000;j++)
{for(int i=0;i<N;i++)
{
/*temp=ha[i];
ha[i]=hb[i];
hb[i]=temp;*/
temp=ha[i]+hb[i];
}
}
h_elapsed=clock()-h_start;
cout<<"cpu__"<<h_elapsed<<endl;
/*for(int i=0;i<N;i++)
{
cout<<ha[i]<<"  "<<hb[i]<<endl;
}*/
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值