您的位置:首页 > 编程语言 > C语言/C++

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

2013-02-01 21:54 429 查看
今天买了本新书《高性能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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: