我已经实现了此代码:http://www.cuvilib.com/Reduction.pdf以便计算矩阵元素的总和。在GPU中查找最低速度比CPU慢
但是,在GPU中,它的运行速度比在CPU中慢得多。
我得到了i7处理器和NVIDIA GT 540M显卡。
它应该是这样或其他什么?
编辑:我在Ubuntu 13.04中使用上述代码的第3版,并使用Eclipse Nsight进行编译。矩阵的大小是2097152个元素。它在3.6 ms内执行,而CPU版本在1.0 ms左右。下面是整个代码:
#include <stdio.h>
#include <stdlib.h>
#include <thrust/sort.h>
#include <sys/time.h>
#include <omp.h>
#include <iostream>
#include <algorithm>
#define MIN(a,b) (((a)<(b))?(a):(b))
static const int WORK_SIZE = 2097152;
int find_min(int *a,int length){
int min = a[0];
for (int i=1;i<length;i++)
if (a[i]<min)
min=a[i];
return min;
}
__global__ static void red_min(int *g_idata,int *g_odata) {
extern __shared__ int sdata[];
unsigned int tid = threadIdx.x;
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
sdata[tid]= g_idata[i];
__syncthreads();
for(unsigned int s=blockDim.x/2; s > 0; s >>= 1) {
if (tid<s) {
sdata[tid] = MIN(sdata[tid],sdata[tid + s]);
}
__syncthreads();
}
if (tid == 0)
g_odata[blockIdx.x] = sdata[0];
}
int main(void) {
int *d1,*d2;
int i,*result;
int *idata,*fdata;
srand (time(NULL));
result = (int *)malloc(sizeof(int));
idata = (int *)malloc(WORK_SIZE*sizeof(int));
fdata = (int *)malloc(WORK_SIZE*sizeof(int));
cudaMalloc((int**)&d1,WORK_SIZE*sizeof(int));
cudaMalloc((int**)&d2,WORK_SIZE*sizeof(int));
for (i = 0; i < WORK_SIZE; i++){
idata[i] = rand();
fdata[i] = i;
}
struct timeval begin, end;
gettimeofday(&begin, NULL);
*result = find_min(idata,WORK_SIZE);
printf("Minimum Element CPU: %d \n", *result);
gettimeofday(&end, NULL);
int time = (end.tv_sec * (unsigned int)1e6 + end.tv_usec) - (begin.tv_sec * (unsigned int)1e6 + begin.tv_usec);
printf("Microseconds elapsed CPU: %d\n", time);
cudaMemcpy(d1,idata,WORK_SIZE*sizeof(int),cudaMemcpyHostToDevice);
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start,0);
int num_blocks = 16384;
bool flag = true;
while (num_blocks>0){
if (flag) {
red_min<<<num_blocks,128,128*sizeof(int)>>>(d1,d2);
}
else {
red_min<<<num_blocks,128,128*sizeof(int)>>>(d2,d1);
}
num_blocks /= 128;
flag = !flag;
}
该演示文稿中有许多不同版本的代码。我们不知道您正在处理的是什么尺寸的阵列。像编译代码的许多细节也会影响性能。您没有提及您使用的是哪种CUDA版本,以及您是在Linux还是Windows。尽管您将该演示文稿链接起来,但您几乎没有提供任何信息。显示完整的代码,显示如何编译它,并显示实际测量结果和输出。然后有人可以帮助你。 –
请提供您的*完整*代码。我希望看到一切。这不清楚吗? –
@ user2424276使用分析器。 – gpuguy