device.cpp 1.72 KB
Newer Older
Chao Liu's avatar
Chao Liu committed
1
2
3
4
5
6
7
8
9
#include "device.hpp"

DeviceMem::DeviceMem(std::size_t mem_size) : mMemSize(mem_size)
{
    hipGetErrorString(hipMalloc(static_cast<void**>(&mpDeviceBuf), mMemSize));
}

void* DeviceMem::GetDeviceBuffer() { return mpDeviceBuf; }

Chao Liu's avatar
Chao Liu committed
10
11
std::size_t DeviceMem::GetBufferSize() { return mMemSize; }

Chao Liu's avatar
Chao Liu committed
12
13
14
15
16
17
18
19
20
21
22
void DeviceMem::ToDevice(const void* p)
{
    hipGetErrorString(
        hipMemcpy(mpDeviceBuf, const_cast<void*>(p), mMemSize, hipMemcpyHostToDevice));
}

void DeviceMem::FromDevice(void* p)
{
    hipGetErrorString(hipMemcpy(p, mpDeviceBuf, mMemSize, hipMemcpyDeviceToHost));
}

Chao Liu's avatar
Chao Liu committed
23
24
void DeviceMem::SetZero() { hipGetErrorString(hipMemset(mpDeviceBuf, 0, mMemSize)); }

25
DeviceMem::~DeviceMem() { hipGetErrorString(hipFree(mpDeviceBuf)); }
Chao Liu's avatar
Chao Liu committed
26
27
28
29
30

struct KernelTimerImpl
{
    KernelTimerImpl()
    {
Chao Liu's avatar
Chao Liu committed
31
32
        hipGetErrorString(hipEventCreate(&mStart));
        hipGetErrorString(hipEventCreate(&mEnd));
Chao Liu's avatar
Chao Liu committed
33
34
35
36
    }

    ~KernelTimerImpl()
    {
Chao Liu's avatar
Chao Liu committed
37
38
        hipGetErrorString(hipEventDestroy(mStart));
        hipGetErrorString(hipEventDestroy(mEnd));
Chao Liu's avatar
Chao Liu committed
39
40
41
42
    }

    void Start()
    {
Chao Liu's avatar
Chao Liu committed
43
44
        hipGetErrorString(hipDeviceSynchronize());
        hipGetErrorString(hipEventRecord(mStart, nullptr));
Chao Liu's avatar
Chao Liu committed
45
46
47
48
    }

    void End()
    {
Chao Liu's avatar
Chao Liu committed
49
50
        hipGetErrorString(hipEventRecord(mEnd, nullptr));
        hipGetErrorString(hipEventSynchronize(mEnd));
Chao Liu's avatar
Chao Liu committed
51
52
53
54
55
    }

    float GetElapsedTime() const
    {
        float time;
Chao Liu's avatar
Chao Liu committed
56
        hipGetErrorString(hipEventElapsedTime(&time, mStart, mEnd));
Chao Liu's avatar
Chao Liu committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
        return time;
    }

    hipEvent_t mStart, mEnd;
};

KernelTimer::KernelTimer() : impl(new KernelTimerImpl()) {}

KernelTimer::~KernelTimer() {}

void KernelTimer::Start() { impl->Start(); }

void KernelTimer::End() { impl->End(); }

float KernelTimer::GetElapsedTime() const { return impl->GetElapsedTime(); }