-
Notifications
You must be signed in to change notification settings - Fork 102
/
solution.cpp
102 lines (79 loc) · 2.72 KB
/
solution.cpp
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
/*
SYCL Academy (c)
SYCL Academy is licensed under a Creative Commons
Attribution-ShareAlike 4.0 International License.
You should have received a copy of the license along with this
work. If not, see <http://creativecommons.org/licenses/by-sa/4.0/>.
*/
#include "../helpers.hpp"
#include <sycl/sycl.hpp>
class vector_add_1;
class vector_add_2;
void test_item() {
constexpr size_t dataSize = 1024;
int a[dataSize], b[dataSize], r[dataSize];
for (int i = 0; i < dataSize; ++i) {
a[i] = i;
b[i] = i;
r[i] = 0;
}
try {
auto gpuQueue = sycl::queue { sycl::gpu_selector_v };
auto bufA = sycl::buffer { a, sycl::range { dataSize } };
auto bufB = sycl::buffer { b, sycl::range { dataSize } };
auto bufR = sycl::buffer { r, sycl::range { dataSize } };
gpuQueue.submit([&](sycl::handler& cgh) {
sycl::accessor accA { bufA, cgh, sycl::read_only };
sycl::accessor accB { bufB, cgh, sycl::read_only };
sycl::accessor accR { bufR, cgh, sycl::write_only };
cgh.parallel_for<vector_add_1>(
sycl::range { dataSize }, [=](sycl::item<1> itm) {
auto globalId = itm.get_id();
accR[globalId] = accA[globalId] + accB[globalId];
});
});
gpuQueue.throw_asynchronous();
} catch (const sycl::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
for (int i = 0; i < dataSize; ++i) {
SYCLACADEMY_ASSERT(r[i] == i * 2);
}
}
void test_nd_item() {
constexpr size_t dataSize = 1024;
constexpr size_t workGroupSize = 128;
int a[dataSize], b[dataSize], r[dataSize];
for (int i = 0; i < dataSize; ++i) {
a[i] = i;
b[i] = i;
r[i] = 0;
}
try {
auto gpuQueue = sycl::queue { sycl::gpu_selector_v };
auto bufA = sycl::buffer { a, sycl::range { dataSize } };
auto bufB = sycl::buffer { b, sycl::range { dataSize } };
auto bufR = sycl::buffer { r, sycl::range { dataSize } };
gpuQueue.submit([&](sycl::handler& cgh) {
sycl::accessor accA { bufA, cgh, sycl::read_write };
sycl::accessor accB { bufB, cgh, sycl::read_write };
sycl::accessor accR { bufR, cgh, sycl::read_write };
auto ndRange = sycl::nd_range { sycl::range { dataSize },
sycl::range { workGroupSize } };
cgh.parallel_for<vector_add_2>(ndRange, [=](sycl::nd_item<1> itm) {
auto globalId = itm.get_global_id();
accR[globalId] = accA[globalId] + accB[globalId];
});
});
gpuQueue.throw_asynchronous();
} catch (const sycl::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
for (int i = 0; i < dataSize; ++i) {
SYCLACADEMY_ASSERT(r[i] == i * 2);
}
}
int main() {
test_item();
test_nd_item();
}