-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcuVector.h
109 lines (105 loc) · 2.03 KB
/
cuVector.h
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
#include <assert.h>
#include "cutil.h"
//
template <typename T, bool PINNED>
struct cuVector
{
T *dev_pointer;
T *host_pointer;
int size;
cuVector()
{
dev_pointer = NULL;
host_pointer = NULL;
size = 0;
}
cuVector(const int n)
{
dev_pointer = NULL;
host_pointer = NULL;
size = 0;
allocate(n);
}
void init(const T *data, const int _size)
{
assert(_size > 0);
cufree();
allocate(_size);
assert(size == _size);
CUDA_SAFE_CALL(cudaMemcpy(host_pointer, data, size*sizeof(T), cudaMemcpyHostToHost));
}
void copy(const T *data, const int _size)
{
assert(_size <= size);
CUDA_SAFE_CALL(cudaMemcpy(host_pointer, data, _size*sizeof(T), cudaMemcpyHostToHost));
}
~cuVector()
{
cufree();
}
void allocate(int _size)
{
assert(_size > 0);
cufree();
size = _size;
void *p;
CUDA_SAFE_CALL(cudaMalloc(&p, size * sizeof(T)));
assert(p);
dev_pointer = (T*)p;
if (PINNED)
{
CUDA_SAFE_CALL(cudaMallocHost(&p, size * sizeof(T)));
}
else
p = malloc(size*sizeof(T));
assert(p);
host_pointer = (T*)p;
}
void cufree()
{
if (size > 0)
{
CUDA_SAFE_CALL(cudaFree(dev_pointer));
if (PINNED)
{
CUDA_SAFE_CALL(cudaFreeHost(host_pointer));
}
else
free(host_pointer);
dev_pointer = NULL;
host_pointer = NULL;
size = 0;
}
}
void h2d(int count)
{
assert(count <= size);
if (size > 0)
CUDA_SAFE_CALL(cudaMemcpy(dev_pointer, host_pointer, count * sizeof(T), cudaMemcpyHostToDevice));
}
void h2d()
{
if (size > 0)
this->h2d(size);
}
void d2h(int count)
{
assert(count <= size);
if (size > 0)
CUDA_SAFE_CALL(cudaMemcpy(host_pointer, dev_pointer, count * sizeof(T), cudaMemcpyDeviceToHost));
}
void d2h()
{
if (size > 0)
this->d2h(size);
}
T &operator [] (int i)
{
return host_pointer[i];
}
operator T* ()
{
return dev_pointer;
}
T* d() {return dev_pointer;}
};