-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAlgorithmBenchmarking.h
More file actions
332 lines (273 loc) · 12.1 KB
/
AlgorithmBenchmarking.h
File metadata and controls
332 lines (273 loc) · 12.1 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#pragma once
#include "Albert.h"
#include "Belikov.h"
#include "Cunningham.h"
#include "Simulate.h"
#include "alltypes.h"
#include <array>
#include <chrono>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <thread>
#include <vector>
#include <string>
std::string cleanName(std::string name) {
// Çàìåíÿåì ïðîáåëû íà '_'
std::replace(name.begin(), name.end(), ' ', '_');
// Óäàëÿåì ïåðåíîñû ñòðîê è âîçâðàòû êàðåòêè
name.erase(std::remove_if(name.begin(), name.end(), [](char c) { return c == '\n' || c == '\r'; }), name.end());
// Óäàëÿåì ìíîæåñòâåííûå '_': çàìåíÿåì '__' íà '_', ïîêà îíè åñòü
size_t pos;
while ((pos = name.find("__")) != std::string::npos) {
name.replace(pos, 2, "_");
}
// Óäàëÿåì âåäóùèå è trailing '_'
if (!name.empty() && name[0] == '_') name.erase(0, 1);
if (!name.empty() && name.back() == '_') name.pop_back();
return name;
}
// Ôóíêöèÿ äëÿ ïîëó÷åíèÿ èìåíè ìîäåëè ïðîöåññîðà
std::string getProcessorName() {
std::string processorName;
#ifdef _WIN32
// Âûçîâ wmic äëÿ Windows
std::stringstream cmd;
cmd << "wmic cpu get name /value";
FILE* pipe = _popen(cmd.str().c_str(), "r");
if (pipe) {
char buffer[256];
std::string result;
while (fgets(buffer, sizeof(buffer), pipe) != NULL) {
result += buffer;
}
_pclose(pipe);
// Ïàðñèíã: èùåì "Name=" è èçâëåêàåì çíà÷åíèå
size_t pos = result.find("Name=");
if (pos != std::string::npos) {
pos += 5; // Ïðîïóñòèòü "Name="
size_t end = result.find("\n", pos);
processorName = result.substr(pos, end - pos);
}
}
#else
// Äëÿ Linux: èñïîëüçóéòå popen
FILE* pipe = popen("grep 'model name' /proc/cpuinfo | head -1 | cut -d: -f2 | tr -d '\\n'", "r");
if (pipe) {
char buffer[256];
if (fgets(buffer, sizeof(buffer), pipe) != NULL) {
processorName = std::string(buffer);
}
pclose(pipe);
}
#endif
if (processorName.empty()) {
processorName = "Unknown_CPU";
}
// Î÷èùàåì èìÿ
return cleanName(processorName);
}
// Get the number of hardware threads available on the system
int getMaxThreads() {
return std::thread::hardware_concurrency();
}
// Function to run benchmarks across all harmonics and thread counts
void runComprehensiveBenchmark(int num_runs, int& importedharmonics) {
bool isUseImitation = false;
std::cout << "=== COMPREHENSIVE ALGORITHM BENCHMARK ===\n";
int maxThreads = getMaxThreads();
std::cout << "Detected " << maxThreads << " hardware threads.\n";
int maxHarmonics = (selectedModel == 1) ? 360 : 2000;
std::string gravityModelName = (selectedModel == 1) ? "EGM96" : "EGM2008";
std::cout << "Selected model: " << gravityModelName << "\n";
std::cout << "Max harmonics: " << maxHarmonics << "\n";
std::cout << "Number of runs per test: " << num_runs << "\n";
std::cout << "This will take a considerable amount of time...\n\n";
std::cout << "Do you want to proceed? (y/n): ";
char confirm;
std::cin >> confirm;
if (confirm != 'y' && confirm != 'Y') {
std::cout << "Benchmark cancelled.\n";
return;
}
// Create output file
// Ïîëó÷àåì èìÿ ïðîöåññîðà
std::string processorName = getProcessorName();
// Ãåíåðèðóåì èìÿ ôàéëà
std::stringstream filename;
filename << "benchmark_" << processorName << "_" << maxThreads << "_" << num_runs << ".csv";
// Îòêðûâàåì ôàéë
std::ofstream file(filename.str());
//std::ofstream file("benchmark_comprehensive.csv");
if (!file.is_open()) {
std::cerr << "Error: Could not open file for writing.\n";
return;
}
// Write CSV header
file << "Algorithm,Threads,Harmonics,AvgTime_ms,StdDev_ms,TotalTime_ms,Speedup,Efficiency\n";
std::cout << "\nStarting benchmark...\n";
// Iterate through harmonics from 2 to maxHarmonics
for (int nmax = 5; nmax <= maxHarmonics; nmax += 5) {
std::cout << "\n=== Testing with " << nmax << " harmonics ===\n";
// Import harmonics for current nmax
if (importedharmonics < maxHarmonics) {
freeStokes(importedharmonics);
importStokesCombined(gravityModels[selectedModel], maxHarmonics);
importedharmonics = maxHarmonics;
std::cout << "Harmonics imported.\n";
}
// Store baseline single-thread Holmes time for speedup calculation
double baselineTime = 0.0;
// Test Belikov
{
std::cout << "Testing Belikov... ";
std::vector<double> times;
for (int run = 0; run < num_runs; ++run) {
auto coords = generateRandomCoordinates();
double radius = coords[0];
double latitude = coords[1];
double longitude = coords[2];
std::array<double, 3> result{};
auto start = std::chrono::high_resolution_clock::now();
gravityBelikov(radius, latitude, longitude, nmax, result);
if (isUseImitation)
simulate_integrator_and_sofa(27);
auto end = std::chrono::high_resolution_clock::now();
double time = std::chrono::duration<double, std::milli>(end - start).count();
times.push_back(time);
}
// Calculate statistics
double avgTime = 0.0;
for (double t : times) avgTime += t;
avgTime /= num_runs;
double variance = 0.0;
for (double t : times) variance += (t - avgTime) * (t - avgTime);
double stdDev = std::sqrt(variance / num_runs);
double totalTime = avgTime * num_runs;
file << "Belikov,1," << nmax << "," << avgTime << "," << stdDev << ","
<< totalTime << ",N/A,N/A\n";
std::cout << "Done. Avg: " << avgTime << " ms\n";
}
// Test Cunningham
{
std::cout << "Testing Cunningham... ";
std::vector<double> times;
for (int run = 0; run < num_runs; ++run) {
auto coords = generateRandomCoordinates();
double radius = coords[0];
double latitude = coords[1];
double longitude = coords[2];
std::array<double, 3> result{};
auto start = std::chrono::high_resolution_clock::now();
gravityCunningham(radius, latitude, longitude, nmax, result);
if (isUseImitation)
simulate_integrator_and_sofa(27);
auto end = std::chrono::high_resolution_clock::now();
double time = std::chrono::duration<double, std::milli>(end - start).count();
times.push_back(time);
}
// Calculate statistics
double avgTime = 0.0;
for (double t : times) avgTime += t;
avgTime /= num_runs;
double variance = 0.0;
for (double t : times) variance += (t - avgTime) * (t - avgTime);
double stdDev = std::sqrt(variance / num_runs);
double totalTime = avgTime * num_runs;
file << "Cunningham,1," << nmax << "," << avgTime << "," << stdDev << ","
<< totalTime << ",N/A,N/A\n";
std::cout << "Done. Avg: " << avgTime << " ms\n";
}
// Test Holmes with different thread counts (1 to maxThreads)
for (int threadCount = 1; threadCount <= maxThreads; ++threadCount) {
std::cout << "Testing Holmes with " << threadCount << " thread(s)... ";
std::vector<double> times;
using namespace uniorb;
gravity_stokes GravityStokes(_c, _s, nmax, nmax, EARTH_MU, EARTH_RADIUS);
GravityStokes.use_concurrency(threadCount);
for (int run = 0; run < num_runs; ++run) {
auto coords = generateRandomCoordinates();
double radius = coords[0];
double latitude = coords[1];
double longitude = coords[2];
std::array<double, 3> result{};
auto start = std::chrono::high_resolution_clock::now();
GravityStokes.get_acceleration(radius, latitude, longitude, result);
if (isUseImitation)
simulate_integrator_and_sofa(27);
auto end = std::chrono::high_resolution_clock::now();
double time = std::chrono::duration<double, std::milli>(end - start).count();
times.push_back(time);
}
// Calculate statistics
double avgTime = 0.0;
for (double t : times) avgTime += t;
avgTime /= num_runs;
double variance = 0.0;
for (double t : times) variance += (t - avgTime) * (t - avgTime);
double stdDev = std::sqrt(variance / num_runs);
double totalTime = avgTime * num_runs;
// Save baseline for speedup calculation
if (threadCount == 1) {
baselineTime = avgTime;
}
// Calculate speedup and efficiency
double speedup = (threadCount == 1) ? 1.0 : baselineTime / avgTime;
double efficiency = speedup / threadCount;
std::string algoName = "Holmes" + std::to_string(threadCount);
file << algoName << "," << threadCount << "," << nmax << "," << avgTime << ","
<< stdDev << "," << totalTime << "," << speedup << "," << efficiency << "\n";
std::cout << "Done. Avg: " << avgTime << " ms, Speedup: " << speedup << "\n";
}
file.flush(); // Ensure data is written periodically
// Progress indicator
int percentComplete = (int)((double)nmax / maxHarmonics * 100);
std::cout << "Overall progress: " << percentComplete << "%\n";
}
file.close();
std::cout << "\n=== BENCHMARK COMPLETE ===\n";
std::cout << "Results saved to benchmark_comprehensive.csv\n";
}
// Function to display the benchmarking menu
void displayBenchmarkingMenu() {
std::cout << "\nBENCHMARKING MODE MENU:\n"
<< "1. Comprehensive Benchmark (All Harmonics & Threads)\n"
<< "2. Back to Main Menu\n"
<< "Enter choice: ";
}
// Main benchmarking mode handler
void runBenchmarkingMode(int& importedharmonics) {
bool submenu_active = true;
int num_runs = 100; // Default number of runs per test
while (submenu_active) {
displayBenchmarkingMenu();
int option;
std::cin >> option;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "INVALID INPUT. TRY AGAIN.\n";
continue;
}
switch (option) {
case 1: {
std::cout << "Enter number of runs per test (default 100): ";
std::cin >> num_runs;
if (std::cin.fail() || num_runs < 1) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
num_runs = 100;
std::cout << "Invalid input. Using default: 100 runs.\n";
}
runComprehensiveBenchmark(num_runs, importedharmonics);
break;
}
case 2:
submenu_active = false;
break;
default:
std::cout << "INVALID OPTION. TRY AGAIN.\n";
break;
}
}
}