-
Notifications
You must be signed in to change notification settings - Fork 2
/
simpleMemcpy.cu
116 lines (95 loc) · 2.77 KB
/
simpleMemcpy.cu
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <cstdio>
#include <cstdlib>
#include <cinttypes>
#include <cuda_runtime.h>
#include "common.hh"
static __global__ void
f(const uint64_t a[], const uint64_t b[], uint64_t c[], int64_t N)
{
int64_t index = threadIdx.x + blockIdx.x * blockDim.x;
int64_t stride = blockDim.x * gridDim.x;
for (int64_t i = index; i < N; i += stride) {
c[i] = a[i] * b[i];
}
}
static void
doit(const uint64_t a[], const uint64_t b[], uint64_t c[], int64_t N)
{
int blockSize = 256;
int64_t numBlocks = (N + blockSize - 1) / blockSize;
f<<<numBlocks, blockSize>>>(a, b, c, N);
}
int
main(int argc, char *argv[])
{
size_t N = 10000000;
clock_t start_program, end_program;
clock_t start, end;
uint64_t *a, *b, *c;
uint64_t *da, *db, *dc;
size_t count;
if (argc == 2) {
N = checked_strtosize(argv[1]);
}
count = checked_mul(N, sizeof(uint64_t));
/* Initialize context */
check(cudaMallocHost(&a, 128));
check(cudaDeviceSynchronize());
check(cudaFreeHost(a));
start_program = clock();
start = clock();
check(cudaMallocHost(&a, count));
check(cudaMallocHost(&b, count));
check(cudaMallocHost(&c, count));
end = clock();
log("host: MallocHost", start, end);
start = clock();
for (size_t i = 0; i < N; i++) {
a[i] = 3;
b[i] = 5;
}
end = clock();
log("host: init arrays", start, end);
start = clock();
check(cudaMalloc(&da, count));
check(cudaMalloc(&db, count));
check(cudaMalloc(&dc, count));
check(cudaMemcpy(da, a, count, cudaMemcpyHostToDevice));
check(cudaMemcpy(db, b, count, cudaMemcpyHostToDevice));
doit(da, db, dc, N);
check(cudaMemcpy(c, dc, count, cudaMemcpyDeviceToHost));
check(cudaFree(da));
check(cudaFree(db));
check(cudaFree(dc));
end = clock();
log("device: malloc+copy+compute", start, end);
start = clock();
for (size_t i = 0; i < N; i++) {
if (a[i] != 3 || b[i] != 5 || c[i] != 15) {
fprintf(stderr, "unexpected result a: %lu b: %lu c: %lu\n",
a[i], b[i], c[i]);
exit(1);
}
}
end = clock();
log("host: access all arrays", start, end);
start = clock();
for (size_t i = 0; i < N; i++) {
if (a[i] != 3 || b[i] != 5 || c[i] != 15) {
fprintf(stderr, "unexpected result a: %lu b: %lu c: %lu\n",
a[i], b[i], c[i]);
exit(1);
}
}
end = clock();
log("host: access all arrays a second time", start, end);
start = clock();
check(cudaFreeHost(a));
check(cudaFreeHost(b));
check(cudaFreeHost(c));
end = clock();
log("host: free", start, end);
end_program = clock();
log("total", start_program, end_program);
return 0;
}