-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain_CPP_23.cpp
More file actions
465 lines (387 loc) · 16.4 KB
/
Main_CPP_23.cpp
File metadata and controls
465 lines (387 loc) · 16.4 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*! BENCHMARK:
- Big int numbers: 8-bit to 64-bit (max negative and max positive)
- Extreme floating: __float128 or double (auto detect, if 128bit supported, use __float128; else use double)
- Char and String: Classic, Wide, ultra-wide, coloring with ANSI and 8-bit RGB (std::string with fmt)
- Stack and Heap Memory
- Smart memory: Unique, Shared and Weak
- Mem-frag: Using for loop to allocate and deallocate quickly, if mem-frag detected, stop test, print "Mem frag detected! Stopping now" then move to next test
- Threading & Mutex: Multi-thread (4 cores), `for` loop, Memory access, Mutex lock/unlock, Measure total time and CPU usage
- Numbers Brute-forcing: 6 digits, each digit is from 0 to 9
*/
#define NOMINMAX
// Detect compiler
#if defined(__clang__)
#define COMPILER "Clang"
#include <um/Windows.h>
#include <malloc.h>
#elif defined(_MSC_VER)
#define FMT_HEADER_ONLY
#define COMPILER "MSVC"
#include <Windows.h>
#else
#define COMPILER "Unknown"
#endif
#include <limits>
#include <iostream>
#include <chrono>
#include <vector>
#include <string>
#include <memory>
#include <map>
#include <sstream>
#include <iomanip>
#include <cstdint>
#include <sstream>
#include <atomic>
#include <thread>
#include <future>
#include <random>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cstddef>
#include <mutex>
#include <fmt/core.h>
#include <fmt/chrono.h>
#include <fmt/color.h>
#include <format>
using namespace std::chrono_literals;
using str = std::string;
// Styler Namespace for Colored Output
namespace Styler_fmt {
inline str bold(const str& txt) { return "\x1b[1m" + txt + "\x1b[22m"; }
inline str italic(const str& txt) { return "\x1b[3m" + txt + "\x1b[23m"; }
inline str under(const str& txt) { return "\x1b[4m" + txt + "\x1b[24m"; }
inline str strike(const str& txt) { return "\x1b[9m" + txt + "\x1b[29m"; }
inline void hex_to_rgb(uint32_t hex, int& r, int& g, int& b) {
r = (hex >> 16) & 0xFF;
g = (hex >> 8) & 0xFF;
b = hex & 0xFF;
}
inline str ColorFG(const str& txt, uint32_t hex = 0x89E67D, int alpha = 100) {
int r, g, b;
hex_to_rgb(hex, r, g, b);
float a = alpha / 100.0f;
r = static_cast<int>(r * a);
g = static_cast<int>(g * a);
b = static_cast<int>(b * a);
return fmt::format("\x1b[38;2;{};{};{}m{}\x1b[39m", r, g, b, txt);
}
inline str ColorBG(const str& txt, uint32_t hex, int alpha = 100) {
int r, g, b;
hex_to_rgb(hex, r, g, b);
float a = alpha / 100.0f;
r = static_cast<int>(r * a);
g = static_cast<int>(g * a);
b = static_cast<int>(b * a);
return fmt::format("\x1b[48;2;{};{};{}m{}\x1b[49m", r, g, b, txt);
}
inline str styler_all(
const str& text,
uint32_t fg = 0xFFFFFF,
uint32_t bg = 0x000000,
bool is_bold = false,
bool is_italic = false,
bool is_underline = false,
bool is_strike = false,
int alpha = 100
) {
str styled = text;
if (is_strike) styled = strike(styled);
if (is_underline) styled = under(styled);
if (is_italic) styled = italic(styled);
if (is_bold) styled = bold(styled);
styled = ColorFG(styled, fg, alpha);
if (bg != 0x000000)
styled = ColorBG(styled, bg, alpha);
return styled + "\x1b[0m";
}
inline void view_raw(const str& s) {
std::cout << "DEBUG RAW: ";
for (char c : s) {
if (std::isprint(c))
std::cout << c;
else
std::cout << "\\x" << std::hex << (int)(uint8_t)c;
}
std::cout << "\n";
}
}
// ===== BENCHMARKS =====
class Program {
public:
// Benchmark Integer Types
class BigInteger {
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Big Integers", 0xffa500), "");
auto start = std::chrono::high_resolution_clock::now();
int64_t i8 = INT8_MAX, i16 = INT16_MAX, i32 = INT32_MIN, i64 = INT64_MIN;
uint64_t u8 = UINT8_MAX, u16 = UINT16_MAX, u32 = UINT32_MAX, u64 = UINT64_MAX;
// Do something with them to prevent optimization
i8 -= 1; u8 += 1;
i16 *= -1; u16 += 1;
i32 /= -1; u32 *= 2;
i64 %= 999999; u64 >>= 1;
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Time taken: {} ns", duration);
}
};
// Benchmark Floating Points
class XtremeFloat {
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Extreme Floats", 0xff4500), "");
auto start = std::chrono::high_resolution_clock::now();
// Ensure we undefine the Windows macros before using numeric_limits
auto FLT_MAX_val = std::numeric_limits<float>::max();
auto DBL_MAX_val = std::numeric_limits<long double>::max();
using fp = double; // Fallback to double if __float128 not supported
fp f1 = static_cast<fp>(FLT_MAX_val) / 2;
fp f2 = static_cast<fp>(DBL_MAX_val) / 1000;
fp f3 = fp(1) / 3;
volatile fp result = f1 + f2 * f3;
(void)result; // Prevent unused warning
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Time taken: {} ns", duration);
}
};
// Benchmark Strings and ANSI Coloring
class Strings {
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Strings & ANSI", 0x00ccff), "");
auto start = std::chrono::high_resolution_clock::now();
// char cstr[] = "classic string";
// wchar_t wcstr[] = L"wide string";
// char8_t utf8str[] = u8"UTF-8 string";
// ANSI coloring via fmt
/**! WARNING:
* no instance of constructor "std::__1::basic_string<_CharT, _Traits, _Allocator>::basic_string [with _CharT=char, _Traits=std::__1::char_traits<char>, _Allocator=std::__1::allocator<char>]" matches the argument listC/C++(289)
* main.cpp(174, 55): argument types are: (char8_t [13])
*/
char cstr[] = "classic string";
wchar_t wcstr[] = L"wide string";
char16_t utf8str[] = u"UTF-8 string";
// ANSI coloring via fmt
fmt::println("{}", Styler_fmt::styler_all(std::string(reinterpret_cast<const char*>(utf8str)), 0xa0522d, 0xffffff, true, false, true, false, 100));
fmt::println("{}", Styler_fmt::styler_all("ANSI colored string", 0x00ff00, 0x0000ff, true, true, true, false, 100));
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Time taken: {} ns", duration);
}
};
// Stack Allocation Benchmark
class StackBench {
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Stack Allocations", 0x9acd32), "");
auto start = std::chrono::high_resolution_clock::now();
constexpr size_t N = 1'000'000;
for (size_t i = 0; i < N; ++i) {
int stackVal = i % 100;
(void)stackVal;
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Stack allocations time: {} ns", duration);
}
};
// Heap Allocation Benchmark
class HeapBench {
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Heap Allocations", 0x8A2BE2), "");
auto start = std::chrono::high_resolution_clock::now();
constexpr size_t N = 1'000'000;
for (size_t i = 0; i < N; ++i) {
auto ptr = new int(i);
delete ptr;
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Heap allocations time: {} ns", duration);
}
};
// Smart Pointer Benchmark
class Smarts {
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Smart Pointers", 0xff69b4), "");
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 100'000; ++i) {
auto uptr = std::make_unique<int>(i);
auto sptr = std::make_shared<int>(i);
std::weak_ptr<int> wptr = sptr;
(void)uptr; (void)sptr; (void)wptr.lock();
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Smart pointer operations time: {} ns", duration);
}
};
// Memory Fragmentation Test
class MemFragTest {
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Memory Fragmentation", 0xff4500), "");
std::vector<void*> allocations;
auto start = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < 10'000'000; ++i) {
void* p = malloc(16);
if (!p) {
fmt::println("Mem frag detected! Stopping now");
break;
}
allocations.push_back(p);
if (i % 10 == 0) {
free(allocations.back());
allocations.pop_back();
}
}
for (auto p : allocations) free(p);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Memory fragmentation test completed in: {} ns", duration);
}
};
// Threading and Mutex Benchmark
class ThreadMutex {
std::mutex mtx;
std::atomic<bool> done = false;
std::vector<int> shared_data;
void worker() {
for (int i = 0; !done.load(); i++) {
std::lock_guard<std::mutex> lock(mtx);
shared_data.push_back(i);
}
}
public:
void main() {
fmt::println("Benchmark: {}{}", Styler_fmt::ColorFG("Threading & Mutex", 0xff00ff), "");
auto start = std::chrono::high_resolution_clock::now();
std::vector<std::thread> workers;
for (int i = 0; i < 4; ++i) {
workers.emplace_back([this]() { worker(); });
}
std::this_thread::sleep_for(2s); // Run for 2 seconds
done.store(true);
for (auto& t : workers) t.join();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Total thread operations: {}", shared_data.size());
fmt::println(" > Thread execution time: {} ns", duration);
}
};
// Brute-force 6-digit number generator
class NumberBruteForce {
std::atomic<size_t> count{0};
std::atomic<bool> found{false};
public:
void main() {
fmt::println("Benchmark:{}{}", Styler_fmt::ColorFG(" 6-Digit Brute Force", 0x00ffff), "");
auto start = std::chrono::high_resolution_clock::now();
auto worker = [this](int tid, int total_threads) {
for (int i = tid; !found.load(); i += total_threads) {
char buffer[7];
std::snprintf(buffer, sizeof(buffer), "%06d", i);
if (std::string(buffer) == "999999") {
found.store(true);
count.fetch_add(1);
break;
}
count.fetch_add(1);
}
};
constexpr int THREAD_COUNT = 4;
std::vector<std::thread> threads;
// for (int i = 0; i < THREAD_COUNT; ++i){
// //! WARNING: an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture listC/C++(1735)
// threads.emplace_back([this, THREAD_COUNT, i](){ worker(i, THREAD_COUNT); });
// };
for (int i = 0; i < THREAD_COUNT; ++i) threads.emplace_back([=](){ worker(i, THREAD_COUNT); });
for (auto& t : threads) t.join();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
fmt::println(" > Brute force complete at iteration: {}", count.load());
fmt::println(" > Execution time: {} ns", duration);
}
};
// Full Benchmark Executor
static void main() {
fmt::println("{}{}", Styler_fmt::styler_all("Starting Benchmark...", 0xffff00, 0x000000, true, false, false, false, 100), "");
BigInteger bigInt;
XtremeFloat extFloat;
Strings strings;
StackBench stack;
HeapBench heap;
Smarts smart;
MemFragTest frag;
ThreadMutex thread;
NumberBruteForce brute;
fmt::println("");
bigInt.main();
fmt::println("");
extFloat.main();
fmt::println("");
strings.main();
fmt::println("");
stack.main();
fmt::println("");
heap.main();
fmt::println("");
smart.main();
fmt::println("");
frag.main();
fmt::println("");
thread.main();
fmt::println("");
brute.main();
fmt::println("{}{}", Styler_fmt::ColorFG("Benchmark Complete!", 0x00ff00), "");
}
};
// Terminal size
int TerminalSize(const char* COR = "X", int offset = 0) {
CONSOLE_SCREEN_BUFFER_INFO CSBI;
// Get console screen buffer info
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &CSBI)) {
fprintf(stderr, "Failed to retrieve console screen buffer info.\n");
return -1; // Indicate failure
}
// Calculate columns and rows
int columns = CSBI.srWindow.Right - CSBI.srWindow.Left + 1;
int rows = CSBI.srWindow.Bottom - CSBI.srWindow.Top + 1;
// Handle input based on COR
if (strcmp(COR, "D") == 0) {
printf("Columns: %d\n", columns);
printf("Rows: %d\n", rows);
return 0; // Indicate success
} else if (strcmp(COR, "X") == 0) {
return columns + offset;
} else if (strcmp(COR, "Y") == 0) {
return rows + offset;
} else {
return 0; // Default return value for invalid input
}
}
int main() {
fmt::println("{:-^{}}", fmt::format(" BENCH {} ", COMPILER), TerminalSize());
DWORD processID = GetCurrentProcessId();
fmt::println("Process ID : {}", processID);
#ifdef __clang__
fmt::println("{}", Styler_fmt::ColorFG("Compiler: LLVM Clang", 0x00ccff));
#elif _MSC_VER
fmt::println("{}", Styler_fmt::ColorFG("Compiler: Microsoft MSVC", 0xffd700));
#else
fmt::println("{}", Styler_fmt::ColorFG("Unknown Compiler Detected", 0xff4500));
fmt::println("{}", Styler_fmt::ColorFG("This is a benchmark for LLVM Clang and MSVC.", 0xffa07a));
#endif
Program::main();
// fmt::println("{}", Styler_fmt::ColorFG("Press Enter to Exit...", 0x00ffff));
fmt::println("{}", Styler_fmt::ColorFG("Exiting now..."));
// std::cin.get();
return 0;
fmt::println("{:-^{}}", fmt::format(" BENCH {} ", COMPILER), TerminalSize());
}