-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope_timer.hpp
66 lines (59 loc) · 1.74 KB
/
scope_timer.hpp
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
#ifndef SCOPETIMER__H
#define SCOPETIMER__H
#include <iostream>
#include <chrono>
enum class TimerPlatForm
{
CPU = 1,
GPU = 2,
};
template <TimerPlatForm platform>
struct ScopeTimer
{
std::chrono::high_resolution_clock::time_point start;
cudaEvent_t event_start, event_end;
float elapsed = 0.0f;
const char* title;
ScopeTimer()
{
title = nullptr;
if constexpr (platform == TimerPlatForm::CPU) {
start = std::chrono::high_resolution_clock::now();
} else if constexpr (platform == TimerPlatForm::GPU) {
cudaEventCreate(&event_start);
cudaEventCreate(&event_end);
cudaEventRecord(event_start);
}
}
ScopeTimer(const char* title)
{
this->title = title;
if constexpr (platform == TimerPlatForm::CPU) {
start = std::chrono::high_resolution_clock::now();
} else if constexpr (platform == TimerPlatForm::GPU) {
cudaEventCreate(&event_start);
cudaEventCreate(&event_end);
cudaEventRecord(event_start);
}
}
~ScopeTimer()
{
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using std::chrono::milliseconds;
if constexpr (platform == TimerPlatForm::CPU) {
auto end = std::chrono::high_resolution_clock::now();
auto duration_ns = duration_cast<nanoseconds>(end - start);
auto duration_ms = duration_cast<milliseconds>(end - start);
std::cout << (title ? title : "") << ": " << duration_ns.count() << " ns\t" << duration_ms.count() << " ms\n";
} else if constexpr (platform == TimerPlatForm::GPU) {
cudaEventRecord(event_end);
cudaEventSynchronize(event_end);
cudaEventElapsedTime(&elapsed, event_start, event_end);
std::cout << (title ? title : "") << ": " << elapsed << " ms\n";
cudaEventDestroy(event_start);
cudaEventDestroy(event_end);
}
}
};
#endif