-
Notifications
You must be signed in to change notification settings - Fork 1
/
vector_add.cpp
71 lines (56 loc) · 1.8 KB
/
vector_add.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
#include <cudawrappers/cu.hpp>
#include <cudawrappers/nvrtc.hpp>
#include <iostream>
void vector_add() {
int N = 1024;
size_t bytesize = N * sizeof(float);
cu::Device device(0);
cu::Context context(CU_CTX_SCHED_BLOCKING_SYNC, device);
cu::HostMemory h_a(bytesize);
cu::HostMemory h_b(bytesize);
cu::HostMemory h_c(bytesize);
float *a = (float *)h_a;
float *b = (float *)h_b;
float *c = (float *)h_c;
for (int i = 0; i < N; i++) {
a[i] = 1.0;
b[i] = 1.0;
c[i] = 0.0;
}
cu::DeviceMemory d_a(bytesize);
cu::DeviceMemory d_b(bytesize);
cu::DeviceMemory d_c(bytesize);
cu::Stream my_stream;
my_stream.memcpyHtoDAsync(d_a, a, bytesize);
my_stream.memcpyHtoDAsync(d_b, b, bytesize);
// compile kernel
extern const char _binary_vector_add_kernel_cu_start,
_binary_vector_add_kernel_cu_end;
const std::string kernel(&_binary_vector_add_kernel_cu_start,
&_binary_vector_add_kernel_cu_end);
std::vector<std::string> options = {};
nvrtc::Program program(kernel, "vector_add_kernel.cu");
try {
program.compile(options);
} catch (nvrtc::Error &error) {
std::cerr << program.getLog();
throw;
}
cu::Module module(static_cast<const void *>(program.getPTX().data()));
cu::Function function(module, "vector_add");
// call kernel
std::vector<const void *> parameters = {d_c.parameter(), d_a.parameter(),
d_b.parameter(), &N};
my_stream.launchKernel(function, 1, 1, 1, 1024, 1, 1, 0, parameters);
my_stream.memcpyDtoHAsync(c, d_c, bytesize);
my_stream.synchronize();
std::cout << "hurray! " << c[0] << " \n";
}
int main(int argc, char *argv[]) {
try {
cu::init();
vector_add();
} catch (cu::Error &error) {
std::cerr << "cu::Error: " << error.what() << std::endl;
}
}