【发布时间】:2014-12-13 11:26:04
【问题描述】:
我有兴趣将我主要使用 Thrust GPU 库编写的代码移植到多核 CPU。值得庆幸的是,the website 表示推力代码可用于 OpenMP / Intel TBB 等线程环境。
我在下面编写了一个简单的代码,用于对大型数组进行排序,以查看使用最多可支持 16 个 Open MP 线程的机器的加速。
在这台机器上对大小为 1600 万的随机数组进行排序得到的时序是
STL:1.47 秒
推力(16 线程):1.21 秒
似乎几乎没有任何加速。我想知道如何像使用 GPU 一样使用 OpenMP 来大幅加快对数组进行排序的速度。
代码如下(文件 sort.cu)。编译如下:
nvcc -O2 -o sort sort.cu -Xcompiler -fopenmp -DTHRUST_DEVICE_SYSTEM=THRUST_DEVICE_BACKEND_OMP -lgomp
NVCC 版本是 5.5 使用的 Thrust 库版本是 v1.7.0
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <ctime>
#include <time.h>
#include "thrust/sort.h"
int main(int argc, char *argv[])
{
int N = 16000000;
double* myarr = new double[N];
for (int i = 0; i < N; ++i)
{
myarr[i] = (1.0*rand())/RAND_MAX;
}
std::cout << "-------------\n";
clock_t start,stop;
start=clock();
std::sort(myarr,myarr+N);
stop=clock();
std::cout << "Time taken for sorting the array with STL is " << (stop-start)/(double)CLOCKS_PER_SEC;
//--------------------------------------------
srand(1);
for (int i = 0; i < N; ++i)
{
myarr[i] = (1.0*rand())/RAND_MAX;
//std::cout << myarr[i] << std::endl;
}
start=clock();
thrust::sort(myarr,myarr+N);
stop=clock();
std::cout << "------------------\n";
std::cout << "Time taken for sorting the array with Thrust is " << (stop-start)/(double)CLOCKS_PER_SEC;
return 0;
}
【问题讨论】:
-
不要使用clock(),使用
omp_get_wtime()。排序是我一直想要研究的东西,但由于它是nlog(n),我的猜测是该操作受内存带宽限制,因此它不能从多个快速内核中受益匪浅。 GPU(或至强融核)的情况有所不同,因为“核心”速度与内存速度之间的比率要低得多。
标签: multithreading sorting thrust