-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdevArray.cuh
109 lines (93 loc) · 1.73 KB
/
devArray.cuh
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
#pragma once
#ifndef DEVARRAY_CUH
#define DEVARRAY_CUH
#include "stdafx.h"
#include "handle_error.cuh"
#include <cuda.h>
using namespace std;
template <class T>
class DevArray
{
// public functions
public:
explicit DevArray()
: start_(0),
end_(0)
{}
// constructor
explicit DevArray(size_t size)
{
allocate(size);
}
// destructor
~DevArray()
{
free();
}
// resize the vector
void resize(size_t size)
{
free();
allocate(size);
}
// get the size of the array
size_t getSize() const
{
return end_ - start_;
}
// get data
const T* getData() const
{
return start_;
}
T* getData()
{
return start_;
}
// set from host
void set(const T *src, size_t size)
{
size_t min = std::min(size, getSize());
HANDLE_ERROR(cudaMemcpy(start_, src, min * sizeof(T), cudaMemcpyHostToDevice));
}
// get to host
void get(T *dest, size_t size)
{
size_t min = std::min(size, getSize());
HANDLE_ERROR(cudaMemcpy(dest, start_, min * sizeof(T), cudaMemcpyDeviceToHost));
}
// set from device
void set(const DevArray<T> *src, size_t size)
{
size_t min = std::min(size, getSize());
HANDLE_ERROR(cudaMemcpy(
start_, src->getData(), min * sizeof(T), cudaMemcpyDeviceToDevice));
}
// get to device
void get(DevArray<T> *dest, size_t size)
{
size_t min = std::min(size, getSize());
HANDLE_ERROR(cudaMemcpy(
dest->getData(), start_, min * sizeof(T), cudaMemcpyDeviceToDevice));
}
// private functions
private:
// allocate memory on the device
void allocate(size_t size)
{
HANDLE_ERROR(cudaMalloc((void**)&start_, size * sizeof(T)));
end_ = start_ + size;
}
// free memory on the device
void free()
{
if (start_ != 0)
{
cudaFree(start_);
start_ = end_ = 0;
}
}
T* start_;
T* end_;
};
#endif