2013-03-07 54 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