-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcppJoules.cpp
More file actions
284 lines (237 loc) · 7.61 KB
/
cppJoules.cpp
File metadata and controls
284 lines (237 loc) · 7.61 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// ============================================================
// cppJoules.cpp -- Windows / Intel Power Gadget 3.6 only
// Merged: RAPLDevice + EnergyTracker implementations
// ============================================================
#include "cppJoules.h"
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
// ============================================================
// Helper: load a function from the already-opened handler
// ============================================================
namespace {
template<typename FnPtr>
FnPtr getFunc(HINSTANCE lib, const char* name)
{
return reinterpret_cast<FnPtr>(GetProcAddress(lib, name));
}
} // anonymous namespace
// ============================================================
// RAPLDevice
// ============================================================
RAPLDevice::RAPLDevice()
{
// Locate EnergyLib64.dll in System32
char sysDir[MAX_PATH] = {};
GetSystemDirectoryA(sysDir, MAX_PATH);
std::string dllPath = std::string(sysDir) + "\\EnergyLib64.dll";
handler = LoadLibraryA(dllPath.c_str());
if (!handler)
{
std::cerr << "[cppJoules] Could not load EnergyLib64.dll from "
<< dllPath << "\n"
<< " Make sure Intel Power Gadget 3.6 is installed.\n";
return;
}
// ── Initialize the library ──────────────────────────────
auto _Init = getFunc<fn_void>(handler, "IntelEnergyLibInitialize");
auto _GetNumMsrs = getFunc<fn_intp>(handler, "GetNumMsrs");
auto _GetNumNodes = getFunc<fn_intp>(handler, "GetNumNodes");
auto _GetMsrFunc = getFunc<fn_int_intp>(handler, "GetMsrFunc");
auto _GetMsrName = getFunc<fn_int_wcp>(handler, "GetMsrName");
if (!_Init || !_GetNumMsrs || !_GetNumNodes || !_GetMsrFunc || !_GetMsrName)
{
std::cerr << "[cppJoules] Failed to resolve required functions from EnergyLib64.dll.\n";
FreeLibrary(handler);
handler = nullptr;
return;
}
_Init();
int numMsrs = 0; _GetNumMsrs(&numMsrs);
int numNodes = 0; _GetNumNodes(&numNodes);
// ── Discover power domains ──────────────────────────────
// We only care about MSR_FUNC_POWER entries.
wchar_t nameBuf[128] = {};
for (int node = 0; node < numNodes; ++node)
{
for (int msr = 0; msr < numMsrs; ++msr)
{
int func = 0;
_GetMsrFunc(msr, &func);
if (func == MSR_FUNC_POWER)
{
_GetMsrName(msr, nameBuf);
//std::wstring ws(nameBuf);
//std::string key(ws.begin(), ws.end());
//key += "-" + std::to_string(node); // e.g. "Processor-0", "IA-0"
//devices[key] = { node, msr };
std::wstring ws(nameBuf);
// Proper wide-to-narrow conversion using the Windows API.
// Power Gadget names are pure ASCII so this is always safe,
// but WideCharToMultiByte is the correct MSVC way to do it.
int len = WideCharToMultiByte(
CP_ACP, // code page: system default (ANSI)
0, // no flags
ws.c_str(), // source wide string
-1, // -1 means "read until null terminator"
nullptr, // no output yet — just measuring length
0,
nullptr, nullptr);
std::string key(len - 1, '\0'); // len includes the null, subtract it
WideCharToMultiByte(
CP_ACP, 0,
ws.c_str(), -1,
&key[0], len, // write into the string's buffer
nullptr, nullptr);
key += "-" + std::to_string(node);
devices[key] = { node, msr };
}
}
}
}
RAPLDevice::~RAPLDevice()
{
if (handler) FreeLibrary(handler);
}
std::map<std::string, unsigned long long> RAPLDevice::getEnergy()
{
std::map<std::string, unsigned long long> energies;
if (!handler) return energies; // DLL not loaded → return empty
auto _ReadSample = getFunc<fn_bool>(handler, "ReadSample");
auto _GetPowerData = getFunc<fn_iidp_ip>(handler, "GetPowerData");
if (!_ReadSample || !_GetPowerData) return energies;
// ReadSample() must be called before GetPowerData().
// The very first call only "primes" the hardware counters,
// so we return zeros and flip the initialized flag.
_ReadSample();
for (const auto& dev : devices)
{
double data[10] = {};
int nData = 0;
if (initialized)
{
_GetPowerData(dev.second.first, dev.second.second, data, &nData);
// data[1] = cumulative energy in mWh
//energies[dev.first] = static_cast<unsigned long long>(data[1]);
//
// Convert mWh → mJ (1 mWh = 3600 mJ) for finer resolution
energies[dev.first] = static_cast<unsigned long long>(data[1] * 3600.0);
}
else
{
energies[dev.first] = 0ULL;
}
}
if (!initialized) initialized = true;
return energies;
}
// ============================================================
// EnergyTracker
// ============================================================
EnergyTracker::EnergyTracker()
{
rapl_device = new RAPLDevice();
}
EnergyTracker::~EnergyTracker()
{
delete rapl_device;
}
void EnergyTracker::start()
{
if (state == STARTED)
{
std::cout << "[cppJoules] Tracker already started.\n";
return;
}
auto ts = std::chrono::system_clock::now();
auto reading = rapl_device->getEnergy();
energy_readings.emplace_back(ts, reading);
state = STARTED;
}
void EnergyTracker::stop()
{
if (state == UNINITIALIZED)
{
std::cout << "[cppJoules] Tracker was never started.\n";
return;
}
if (state == STOPPED)
{
std::cout << "[cppJoules] Tracker already stopped.\n";
return;
}
auto ts = std::chrono::system_clock::now();
auto reading = rapl_device->getEnergy();
energy_readings.emplace_back(ts, reading);
state = STOPPED;
}
void EnergyTracker::calculate_energy()
{
if (state == UNINITIALIZED)
{
std::cout << "[cppJoules] Tracker was never started.\n";
return;
}
if (state != STOPPED)
{
std::cout << "[cppJoules] Call stop() before calculate_energy().\n";
return;
}
last_calculated_energies.clear();
last_calculated_time = 0.f;
// energy_readings is a flat list of alternating start/stop pairs
for (size_t i = 0; i + 1 < energy_readings.size(); i += 2)
{
const auto& start = energy_readings[i];
const auto& stop = energy_readings[i + 1];
last_calculated_time +=
std::chrono::duration<float>(stop.timestamp - start.timestamp).count();
for (const auto& domain : start.energies)
{
const std::string& key = domain.first;
// stop may not have the key if Power Gadget failed mid-run
if (stop.energies.count(key) == 0) continue;
long long delta =
static_cast<long long>(stop.energies.at(key)) -
static_cast<long long>(domain.second);
// Intel Power Gadget counters don't wrap like Linux RAPL,
// but guard against negative deltas from a first-sample prime.
if (delta >= 0)
last_calculated_energies[key] += delta;
}
}
energy_readings.clear(); // reset for potential re-use
state = UNINITIALIZED;
}
void EnergyTracker::print_energy() const
{
if (last_calculated_energies.empty())
{
std::cout << "[cppJoules] No data — call calculate_energy() first.\n";
return;
}
std::cout << "Duration (s): " << last_calculated_time << "\n";
for (const auto& e : last_calculated_energies)
std::cout << e.first << " : " << e.second << " mJ\n";
}
void EnergyTracker::save_csv(const std::string& file) const
{
std::ofstream out(file);
if (!out.is_open())
{
std::cerr << "[cppJoules] Could not open file: " << file << "\n";
return;
}
// Header
out << "Time(s),"; // domain columns already have their names
// (no change needed in csv, but add a comment in the file header)
for (const auto& e : last_calculated_energies)
out << e.first << ",";
out << "\n";
// Values
out << last_calculated_time << ",";
for (const auto& e : last_calculated_energies)
out << e.second << ",";
out << "\n";
}