-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprofiler.hpp
More file actions
76 lines (66 loc) · 1.93 KB
/
profiler.hpp
File metadata and controls
76 lines (66 loc) · 1.93 KB
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
#pragma once
#include <cuda_runtime.h>
#include "tinycuda/error.hpp"
namespace tinycuda {
/**
* @brief KernelProfiler provides untimed warmup followed by repeated timing for CUDA kernel launches.
*
* Example usage:
* tinycuda::KernelProfiler profile(10, 100);
* float avg_ms = profile([&] {
* my_kernel<<<grid, block>>>(args...);
* });
* printf("Avg kernel time: %.4f ms\n", avg_ms);
*/
class KernelProfiler {
public:
/**
* @brief Construct a KernelProfiler
* @param warmup Number of warmup runs before timing
* @param repeat Number of timed runs
*/
KernelProfiler(int warmup = 5, int repeat = 50)
: warmup_(warmup), repeat_(repeat) {}
/**
* @brief Run a kernel launch and measure average execution time in ms
*
* Usage:
* float avg_ms = profile([&] {
* kernel<<<grid, block>>>(...);
* });
*/
template<typename F>
float operator()(F&& kernel_launch) {
// Create CUDA events
cudaEvent_t start, stop;
CUDA_CHECK(cudaEventCreate(&start));
CUDA_CHECK(cudaEventCreate(&stop));
// ---------------------
// Warmup
// ---------------------
for (int i = 0; i < warmup_; ++i) {
kernel_launch();
}
CUDA_CHECK(cudaDeviceSynchronize()); // Ensure warmup complete
// ---------------------
// Timed runs
// ---------------------
CUDA_CHECK(cudaEventRecord(start));
for (int i = 0; i < repeat_; ++i) {
kernel_launch();
}
CUDA_CHECK(cudaEventRecord(stop));
CUDA_CHECK(cudaEventSynchronize(stop));
float ms = 0.0f;
CUDA_CHECK(cudaEventElapsedTime(&ms, start, stop));
ms /= static_cast<float>(repeat_);
// Cleanup
CUDA_CHECK(cudaEventDestroy(start));
CUDA_CHECK(cudaEventDestroy(stop));
return ms;
}
private:
int warmup_;
int repeat_;
};
} // namespace tinycuda