Cuda C++ Thrust API与 Cuda Runtime API程序比较

今天买了本新书《高性能CUDA应用设计与开发方法与最佳实践》,今天读了第一章有点出获,分享给大家。

程序功能:给向量填充数据并计算各元素之和

1. CPU串行运行的代码:

//seqSerial.cpp:串行执行数组的填充及求和
#include<iostream>
#include<vector>
using namespace std;

int main()
{
 const int N=50000;
 //任务1:创建数组
 vector<int> a(N);
 //任务2:填充数组
 for(int i=0;i<N;i++)a[i]=i;
 //任务3:计算数组各元素之和
 int sumA=0;
 for(int i=0;i<N;i++)sumA+=a[i];
 //任务4:计算0-N-1之和
 int sumCheck=0;
 for(int i=0;i<N;i++)sumCheck+=i;
 //任务5:检查结果是否正确
 if(sumA==sumCheck) cout<<"Test Succeeded!"<<endl;
 else {cerr<<"TestFailed!"<<endl;return(1);}
 return (0);
}

 2.Cuda Thrust C++ API 程序

#include<iostream>
using namespace std;

#include<thrust\/reduce.h>
#include<thrust/sequence.h>
#include<thrust/host_vector.h>
#include<thrust/device_vector.h>

int main()
{
 const int N=50000;
 //任务1:创建数组
 thrust::device_vector<int>a(N);
 //任务2:填充数组,并行运算
 thrust::sequence(a.begin(),a.end(),0);
 //任务3:计算数组元素之和,并行计算
 int sumA=thrust::reduce(a.begin(),a.end(),0);
 //
 int sumCheck=0;
 for(int i=0;i<N;i++)
  sumCheck+=i;
 //
 if(sumA==sumCheck)cout<<"Test Succeeded!"<<endl;
 else
 {
  cerr<<"Test Failed!"<<endl;
  return(1);
 }
 getchar();
 return (0);
}

 

3.仅对数据填充改为Runtime API 程序

//使用cuda Runtime API完成向数组中填充连续整数
#include<iostream>
using namespace std;

#include<thrust\/reduce.h>
#include<thrust/sequence.h>
#include<thrust/host_vector.h>
#include<thrust/device_vector.h>

__global__ void fillKernel(int *a,int n)
{
 int tid=blockIdx.x*blockDim.x+threadIdx.x;
 if(tid<n) a[tid]=tid;
}

void fill(int *d_a,int n)
{
 int nThreadsPerBlock=512;
 //int nBlocks=n/nThreadsPerBlock+(n%nThreadsPerBlock)?1:0);
 int nBlocks=(n+nThreadsPerBlock)/nThreadsPerBlock;
 fillKernel<<<nBlocks,nThreadsPerBlock>>>(d_a,n);
}

int main()
{
 const int N=50000;
 //任务1:创建数组
 thrust::device_vector<int>a(N);
 //任务2:填充数组,使用Runtime API 填充数组
 fill(thrust::raw_pointer_cast(&a[0]),N);
 //任务3:计算数组元素之和,并行计算
 int sumA=thrust::reduce(a.begin(),a.end(),0);
 //任务4:计算0-N-1之和
 int sumCheck=0;
 for(int i=0;i<N;i++)
  sumCheck+=i;
 //任务5:检查结果的正确性
 if(sumA==sumCheck)cout<<"Test Succeeded!"<<endl;
 else
 {
  cerr<<"Test Failed!"<<endl;
  return(1);
 }
 getchar();
 return (0);
}

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值