Ich habe 2000 2D-Arrays (jedes Array ist 1000x1000) Ich muss den Mittelwert jedes Computers berechnen und das Ergebnis in einen 2000 Vektor setzen.Berechnen des Mittelwerts von 2000 2D-Arrays mit CUDA C
Ich habe versucht, indem ich den Kernel für jedes 2D-Array, aber es ist naiv, ich möchte die Berechnung auf einmal tun.
Dies ist, was ich getan habe, ist ein Kernel für ein 2D-Array. Ich möchte Kernel dazu bringen dies für 2000 2D-Arrays in einem Kernel zu tun.
#include <stdio.h>
#include <cuda.h>
#include <time.h>
void init_mat(float *a, const int N, const int M);
void print_mat(float *a, const int N, const int M, char *d);
void print_array(float *a, const int N, char *d);
const int threadsPerBlock=256;
__global__
void kernel(float *mat, float *out, const int N, const int M){
__shared__ float cache[threadsPerBlock];
int tid=threadIdx.x+blockIdx.x*blockDim.x;
int cacheIndex = threadIdx.x;
float sum=0;
if(tid<M){
for(int i=0; i<N; i++)
sum += mat[(i*M)+tid];
cache[cacheIndex] = sum;
out[tid] =cache[cacheIndex];
}
__syncthreads();
int i = blockDim.x/2;
while(i!=0){
if(cacheIndex<i)
cache[cacheIndex]+= cache[cacheIndex +i];
__syncthreads();
i/=2;
}
if(cacheIndex==0)
out[blockIdx.x]=cache[0];
}
int main (void) {
srand(time(NULL));
float *a, *b, *c;
float *dev_a, *dev_b, *dev_c;
int N=1000;
int M=1000;
b=(float*)malloc(sizeof(float)*N*M);
c=(float*)malloc(sizeof(float)*M);
init_mat(b, N, M);
printf("<<<<<<<<<< initial data:\n");
print_mat(b, N, M, "matrix");
cudaMalloc((void**)&dev_b, sizeof(float)*N*M);
cudaMalloc((void**)&dev_c, sizeof(float)*M);
cudaMemcpy(dev_b, b, sizeof(float)*N*M, cudaMemcpyHostToDevice);
printf("\n\nRunning Kernel...\n\n");
kernel<<<M/256+1, 256>>>(dev_b, dev_c, N, M);
cudaMemcpy(c, dev_c, sizeof(float)*M, cudaMemcpyDeviceToHost);
cudaFree(dev_a);
cudaFree(dev_b);
cudaFree(dev_c);
printf(">>>>>>>>>> final data:\n");
print_array(c, M, "out-vector");
};
void init_mat(float *a, const int N, const int M) {
int i, j;
for(i=0; i<N; i++)
for(j=0; j<M; j++)
a[i*M+j] = rand() % 100 + 1;
}
void print_mat(float *a, const int N, const int M, char *d) {
int i, j;
for(i=0; i<N; i++){
printf("\n%s[%d]:", d, i);
for (j=0; j<M; j++)
printf("\t%6.4f", a[i*M+j]);
}
printf("\n");
}
void print_array(float *a, const int N, char *d) {
int i;
for(i=0; i<N; i++)
printf("\n%s[%d]: %f",d, i, a[i]);
printf("\n");
}
Jede Hilfe Danke
Sie könnten ein ähnliches Verfahren verwenden, was beschrieben wird [hier] (http://stackoverflow.com/questions/42260493/reduce-multiple-blocks-of-equal-length-that-are-arranged- In-einem-großen-Vektor-Verwendung-c). Wenn Sie den Code dessen anzeigen, was Sie gerade getan oder versucht haben, erhalten Sie wahrscheinlich mehr Hilfe. –
Danke. Ich werde setzen, was ich getan habe @ Robert Crovella –