2013-03-07 53 views
-2

我正在学习CUDA。今天,我在书中尝试了一些代码:CUDA Application Design And Development,这让我很惊讶。为什么CUDA Thrust如此之慢?这里是代码和输出。CUDA推力降低如此之慢?

#include <iostream> 
using namespace std; 

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

#include "GpuTimer.h" 

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

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

int main() 
{ 
    const int N = 500000; 
    GpuTimer timer1, timer2; 

    thrust::device_vector<int> a(N); 

    fill(thrust::raw_pointer_cast(&a[0]), N); 

    timer1.Start(); 
    int sumA = thrust::reduce(a.begin(), a.end(), 0); 
    timer1.Stop(); 

    cout << "Thrust reduce costs " << timer1.Elapsed() << "ms." << endl; 

    int sumCheck = 0; 
    timer2.Start(); 
    for(int i = 0; i < N; i++) 
     sumCheck += i; 
    timer2.Stop(); 

    cout << "Traditional reduce costs " << timer2.Elapsed() << "ms." << endl; 
    if (sumA == sumCheck) 
     cout << "Correct!" << endl; 
    return 0; 
} 

enter image description here

+4

也许是因为您的输入数据量很小,或者您的GPU速度太慢,或者您的主机CPU速度很快,或者您的CUDA平台有很多延迟?当我们不知道实验如何进行时,我们如何回答为什么您的特定实验不符合一些任意期望的结果? – talonmies 2013-03-07 09:44:30

回答

5

您没有有效的比较。你的GPU代码是这样做的:

int sumA = thrust::reduce(a.begin(), a.end(), 0); 

你的CPU的代码是这样做的:

for(int i = 0; i < N; i++) 
    sumCheck += i; 

有这么多的问题,这种方法我不知道从哪里开始。首先,GPU操作是一个有效的缩减,它将为矢量a中的任何数字序列提供有效的结果。恰巧你在a有从1到N的序列,但它不一定是这样,它仍然会给出正确的结果。 CPU代码只有给出了特定的序列1到N的正确答案。其次,一个智能编译器可能能够优化你的CPU代码,实质上将整个循环缩减为一个常量赋值语句。 (从1到N的求和只是(N + 1)(N/2)不是吗?)我不知道CPU端可能会进行哪些优化。

一个更有效的比较是在这两种情况下做一个实际的任意减少。一个示例可能是基准推力::减少在设备向量上操作与在主机向量上操作。或者写下你自己的串行CPU缩减代码,它实际上是在一个矢量上运行,而不是将1到N中的整数相加。

如评论中所示,如果您认真想要帮助,请记录硬件和SW平台上运行,并提供所有代码。我不知道GPUtimer是做什么的。我正在投票将其视为“过于本地化”,因为我认为任何人都不会使用这种方法进行有效的比较。

+0

非常感谢。我对CUDA真的很陌生,有时候我对它过于期待。我认为关闭这个问题是一个很好的消化。 – hakunami 2013-03-27 02:50:06