Thrust是cuda自帶的c++庫,cuda安裝好之后,這個庫也默認安裝好了。
這個庫基本是采用類似STL的接口方式,因此對於開發者非常友好,開發者不再需要關注內存與顯存相關的問題了。
下面是一個簡單的排序代碼 main.cu:
#include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/generate.h> #include <thrust/sort.h> #include <thrust/copy.h> #include <algorithm> #include <vector> #include <time.h> int main(void) { thrust::host_vector<int> h_vec(1024*1024); std::generate(h_vec.begin(), h_vec.end(), rand); std::vector<int> vec(h_vec.size()); thrust::copy(h_vec.begin(), h_vec.end(), vec.begin()); thrust::device_vector<int> d_vec = h_vec; clock_t time1,time2; time1 = clock(); thrust::sort(d_vec.begin(), d_vec.end()); time2 = clock(); std::cout<<(double)(time2-time1)/CLOCKS_PER_SEC<<std::endl; time1 = clock(); std::sort(vec.begin(),vec.end()); time2 = clock(); std::cout<<(double)(time2-time1)/CLOCKS_PER_SEC<<std::endl; time1 = clock(); thrust::sort(h_vec.begin(), h_vec.end()); time2 = clock(); std::cout<<(double)(time2-time1)/CLOCKS_PER_SEC<<std::endl; return 0; }
結果如下:
可以看出加速性能還是很好的。