-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex11.cu
More file actions
98 lines (79 loc) · 2.34 KB
/
Copy pathex11.cu
File metadata and controls
98 lines (79 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// CUDA programming
// Exercise n. 11
#include <cuda.h>
#include <stdio.h>
#define N 16 // Number of elements
#define THREADS 8 // Threads per block
// Prototypes
__global__ void prefix_sum(int *input, int *output, int n);
__host__ void initialize_array(int *a, int n);
__host__ void print_array(int *a, int n);
int main(void)
{
int *input, *output; // Host copies
int *d_input, *d_output; // Device copies
int size = N * sizeof(int);
// Allocate space for host arrays
input = (int *)malloc(size);
output = (int *)malloc(size);
// Initialize input array
initialize_array(input, N);
// Allocate space for device arrays
cudaMalloc((void **)&d_input, size);
cudaMalloc((void **)&d_output, size);
// Copy input array to device
cudaMemcpy(d_input, input, size, cudaMemcpyHostToDevice);
// Call the kernel
prefix_sum<<<1, THREADS>>>(d_input, d_output, N);
// Copy results back to host
cudaMemcpy(output, d_output, size, cudaMemcpyDeviceToHost);
// Print results
printf("Input Array:\n");
print_array(input, N);
printf("Prefix Sum (Exclusive):\n");
print_array(output, N);
// Cleanup
free(input);
free(output);
cudaFree(d_input);
cudaFree(d_output);
return EXIT_SUCCESS;
}
// Kernel: Prefix sum (exclusive scan)
__global__ void prefix_sum(int *input, int *output, int n)
{
__shared__ int temp[THREADS]; // Shared memory for computation
int index = threadIdx.x;
// Load elements into shared memory
if (index < n)
temp[index] = input[index];
__syncthreads();
// Compute prefix sum using the shared memory
for (int offset = 1; offset < n; offset *= 2)
{
int value = 0;
if (index >= offset)
value = temp[index - offset];
__syncthreads();
temp[index] += value;
__syncthreads();
}
// Write results back to the output array
if (index < n)
output[index] = (index == 0) ? 0 : temp[index - 1]; // Exclusive scan
}
// Host function to initialize an array
__host__ void initialize_array(int *a, int N)
{
for(int i = 0; i < N; i++)
a[i] = i + 1; // Sequential integers
}
// Host function to print an array
__host__ void print_array(int *a, int N)
{
for(int i = 0; i < N; i++)
{
printf("%d\t", a[i]);
}
printf("\n");
}