# Lösungsvorschlag

#include <cstdio>
#include <cmath>
#include <hpc/cuda/check.h>

#define N 8192

template<typename Index, typename TX, typename TY>
TX dot(Index n, const TX* x, Index incX, TY* y, Index incY) {

TX res = 0;
for (Index index = 0; index < n; ++index) {
res += x[index * incX] * y[index * incY];
}
return res;
}

template<typename Index, typename T>
__global__ void asum(Index n, const T* x, T* sums) {
Index index = threadIdx.x + blockIdx.x * blockDim.x;
if (index < n) {
sums_per_block[me] = x[index];
} else {
sums_per_block[me] = 0;
}
/* aggregate sum within a block */
index = blockDim.x / 2;
while (index) {
if (me < index) {
sums_per_block[me] += sums_per_block[me + index];
}
index /= 2;
}
if (me == 0) {
sums[blockIdx.x] = sums_per_block[0];
}
}

template<typename Index, typename TX, typename TY, typename T>
__global__ void dot(Index n,
const TX* x, Index incX, TY* y, Index incY, T* sums) {
Index index = threadIdx.x + blockIdx.x * blockDim.x;

T res;
if (index < n) {
res = x[index * incX] * y[index * incY];
} else {
res = 0;
}

sums_per_block[me] = res;

/* aggregate sum within a block */
index = blockDim.x / 2;
while (index) {
if (me < index) {
sums_per_block[me] += sums_per_block[me + index];
}
index /= 2;
}
if (me == 0) {
sums[blockIdx.x] = sums_per_block[0];
}
}

int main() {
double a[N]; double b[N];
for (unsigned int i = 0; i < N; ++i) {
a[i] = i; b[i] = i * i;
}

/* transfer vectors to GPU memory */
double* cuda_a;
CHECK_CUDA(cudaMalloc, (void**)&cuda_a, N * sizeof(double));
CHECK_CUDA(cudaMemcpy, cuda_a, a, N * sizeof(double),
cudaMemcpyHostToDevice);
double* cuda_b;
CHECK_CUDA(cudaMalloc, (void**)&cuda_b, N * sizeof(double));
CHECK_CUDA(cudaMemcpy, cuda_b, b, N * sizeof(double),
cudaMemcpyHostToDevice);

double* cuda_sums;
CHECK_CUDA(cudaMalloc, (void**)&cuda_sums, NUM_BLOCKS * sizeof(double));

/* execute kernel function on GPU */
dot<<<NUM_BLOCKS, THREADS_PER_BLOCK>>>(N, cuda_a, 1, cuda_b, 1, cuda_sums);
unsigned int len = NUM_BLOCKS;
while (len > 1) {
double* cuda_sums2;
CHECK_CUDA(cudaMalloc, (void**)&cuda_sums2, num_blocks * sizeof(double));
CHECK_CUDA(cudaFree, cuda_sums); cuda_sums = cuda_sums2;
len = num_blocks;
}

/* transfer result vector from GPU to host memory */
double sum;
CHECK_CUDA(cudaMemcpy, &sum, cuda_sums, sizeof(double),
cudaMemcpyDeviceToHost);
/* free space allocated at GPU memory */
CHECK_CUDA(cudaFree, cuda_a); CHECK_CUDA(cudaFree, cuda_b);
CHECK_CUDA(cudaFree, cuda_sums);

/* print difference to local result */
double local_sum = dot(N, a, 1, b, 1);
std::printf("diff: %12.4lg\n", std::abs(sum - local_sum));
}