Замер скорости выполнения кода в С++20 используя chrono и duration_cast
#include <iostream>
#include <chrono>
int main() {
auto in = std::chrono::high_resolution_clock().now();
for (int i = 0; i <= 300; i++) {
std::cout << " i:" << i << std::endl;
}
auto out = std::chrono::high_resolution_clock().now();
double intime = std::chrono::duration_cast<std::chrono::milliseconds>(out - in).count();
std::cout << " for 0 to 300 ->" << intime <<" ms" << std::endl;
}
Генерация чисел (int,int64_t)
#include <iostream>
#include <random>
#include <string>
uint64_t randU64(uint64_t in_v) {
std::random_device rd; // инициализация движка
std::mt19937 gen(rd()); // инициализация генератора
std::uniform_int_distribution<int64_t> dist(2, in_v);//присвоение типа для генерации
return dist(gen); //генерация чисел
}
int main(int argc, char** argv) {
std::string strInt64Data;
std::cout <<" Random Lib Demo C++ by HCPP STUDIO" << std::endl;
std::cout << " ЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫЫ " << std::endl;
static int64_t i64Value = 0;
if (argc > 0) {
std::cout << " Usage: app.exe 100" << std::endl;
std::cout << "argument:"<<argc <<" none" << std::endl;
std::cout << "Enter any Integer Value:";
std::cin >> i64Value;
}
else {
i64Value = std::stoi(static_cast<const char*>(argv[1]));
}
std::cout << "\nvalue_random:" << randU64(i64Value)
<< "\nvalue_int64:" << i64Value << std::endl;
}
👍1
HCPP DEV | (uint8_t)0x539
обновил трассировщик и теперь вот так ошибка выглядит
//вот код. Если не будет функции то значит нет файла pdb
//Функцию BugReport вызывать в начале int main и потом в конце программы Cleanup();
//Код
#include <dbghelp.h>
#pragma comment(lib, "dbghelp.lib")
struct CPPException {
bool ErrorTextures = false;
std::string sLastError;
void* pLastStack = nullptr;
void log(std::string t) {
std::cout << "Exception Error: " << t << std::endl;
}
void Write(const std::string& t, void* pErrorSegment) {
ErrorTextures = true;
sLastError += t + "\n";
pLastStack = pErrorSegment;
log("EXCEPTIONS::Write: " + t + ", StackPtr: " + std::to_string(reinterpret_cast<uintptr_t>(pErrorSegment)));
}
static std::wstring GetStackTrace(PEXCEPTION_POINTERS pExInfo) {
std::wstringstream ss;
HANDLE process = GetCurrentProcess();
HANDLE thread = GetCurrentThread();
// Инициализация символов
SymInitialize(process, NULL, TRUE); // Загружаем символы для всех модулей
SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); // Включаем линии и имена без декораций
STACKFRAME64 frame = { 0 };
frame.AddrPC.Offset = pExInfo->ContextRecord->Rip;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrFrame.Offset = pExInfo->ContextRecord->Rbp;
frame.AddrFrame.Mode = AddrModeFlat;
frame.AddrStack.Offset = pExInfo->ContextRecord->Rsp;
frame.AddrStack.Mode = AddrModeFlat;
while (StackWalk64(
IMAGE_FILE_MACHINE_AMD64,
process,
thread,
&frame,
pExInfo->ContextRecord,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL)) {
DWORD64 address = frame.AddrPC.Offset;
if (address == 0) break; // Конец стека
// Форматирование адреса
ss << L"[0x" << std::hex << std::setw(16) << std::setfill(L'0') << address << L"] ";
// Получение имени функции
char symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME] = { 0 };
SYMBOL_INFO* symbol = (SYMBOL_INFO*)symbolBuffer;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
DWORD64 displacement = 0;
if (SymFromAddr(process, address, &displacement, symbol)) {
// Конвертация char* в wstring
std::string funcName(symbol->Name);
std::wstring wFuncName(funcName.begin(), funcName.end()); // Простое преобразование (или используйте MultiByteToWideChar для точности)
ss << L"Function: " << wFuncName << L" + 0x" << std::hex << displacement;
}
else {
ss << L"Unknown function";
}
// Получение имени файла и номера строки
IMAGEHLP_LINE64 line = { 0 };
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
DWORD lineDisplacement = 0;
if (SymGetLineFromAddr64(process, address, &lineDisplacement, &line)) {
// Конвертация char* в wstring
std::string fileName(line.FileName);
std::wstring wFileName(fileName.begin(), fileName.end());
ss << L" at " << wFileName << L":" << std::dec << line.LineNumber;
}
// Получение имени модуля
IMAGEHLP_MODULE64 module = { 0 };
module.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if (SymGetModuleInfo64(process, address, &module)) {
// ModuleName — это TCHAR*, в Unicode-проекте это wchar_t*
ss << L" in module " << module.ModuleName;
}
ss << L"\n";
}
// Очистка символов
SymCleanup(process);
return ss.str();
}
Мой логотип движка портировал в линукс
#include <iostream>
#include <string>
#include <format>
void logo(){
struct ColorV4 {
uint8_t r, g, b;
constexpr ColorV4() : r(0), g(0), b(0) {}
constexpr ColorV4(uint8_t _r, uint8_t _g, uint8_t _b) : r(_r), g(_g),b(_b) {}
};
struct ConsoleText{
void pout(const std::string& str, const ColorV4& col) {
std::cout << std::format("\e[38;2;{};{};{}m{}\e[0m",
col.r, col.g, col.b, str);
}
};
std::string PAHOM_ENGINE =
" ______ ______ __ __ ______ __ __ \n"
"/\\ == \\ /\\ __ \\ /\\ \\_\\ \\ /\\ __ \\ /\\ \"-./ \\ \n"
"\\ \\ _-/ \\ \\ __ \\ \\ \\ __ \\ \\ \\ \\/\\ \\ \\ \\ \\-./\\ \\ \n"
" \\ \\_\\ \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\ \\_____\\ \\ \\_\\ \\ \\_\\ \n"
" \\/_/ \\/_/\\/_/ \\/_/\\/_/ \\/_____/ \\/_/ \\/_/ \n"
" \n"
" ______ __ __ ______ __ __ __ ______ \n"
"/\\ ___\\ /\\ \"-.\\ \\ /\\ ___\\ /\\ \\ /\\ \"-.\\ \\ /\\ ___\\ \n"
"\\ \\ __\\ \\ \\ \\-. \\ \\ \\ \\__ \\ \\ \\ \\ \\ \\ \\-. \\ \\ \\ __\\ \n"
" \\ \\_____\\ \\ \\_\\\\\"\\_\\ \\ \\_____\\ \\ \\_\\ \\ \\_\\\\\"\\_\\ \\ \\_____\\ \n"
" \\/_____/ \\/_/ \\/_/ \\/_____/ \\/_/ \\/_/ \\/_/ \\/_____/ \n"
" \n";
ConsoleText Console;
ColorV4 colorText = {
};
for(int logoSize = 0; logoSize <= PAHOM_ENGINE.size();logoSize++){
colorText.r = rand() % 255;
colorText.g = rand() % 255;
colorText.b = rand() % 255;
Console.pout(std::format("{}",PAHOM_ENGINE[logoSize]),colorText);
}
Console.pout("LINUX EDITION",ColorV4(18, 52, 245));
}
int main(int argc,char** argv){
logo();
}
#include <iostream>
#include <string>
#include <format>
struct ColorV4 {
uint8_t r, g, b;
constexpr ColorV4() : r(0), g(0), b(0) {}
constexpr ColorV4(uint8_t _r, uint8_t _g, uint8_t _b) : r(_r), g(_g),b(_b) {}
};
struct ConsoleText{
void pout(const std::string& str, const ColorV4& col,const ColorV4& colBack,bool isBackground = false) {
if(isBackground){
std::cout << std::format("\e[48;2;{};{};{}m\e[38;2;{};{};{}m{}\e[0m",
colBack.r, colBack.g, colBack.b,
col.r, col.g, col.b,
str);
}else{
std::cout << std::format("\e[38;2;{};{};{}m{}\e[0m",
col.r, col.g, col.b, str);
}
}
};
ConsoleText Console;
void GenCubesANSI(int64_t count){
static int64_t _n = 0;
for(int64_t cube = 0; cube < count;cube++){
_n++;
if(_n > (count / 10)){
Console.pout(std::format("\n"),{0,0,0},{0,0,0},false);
_n = 0;
}
Console.pout(" ",
{0,0,0},
ColorV4((rand() % 255),(rand() % 255), (rand() % 255))
,true);
}
}
int main(int argc,char** argv){
logo();
GenCubesANSI(1000);
}
Новый метод отрисовки в движке сменил старый wglCreateContext на новый. Теперь можно управлять версией OpenGL прям в движке.
#include <GL/GL.h>
typedef HGLRC(WINAPI* PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int* attribList);
#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
#define WGL_CONTEXT_FLAGS_ARB 0x2094
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
HGLRC CreateGL(HDC hDC, int major, int minor)
{
HGLRC hRC_temp = wglCreateContext(hDC);
if (!hRC_temp) return NULL;
if (!wglMakeCurrent(hDC, hRC_temp))
{
wglDeleteContext(hRC_temp);
return NULL;
}
wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
if (!wglCreateContextAttribsARB)
{
wglMakeCurrent(NULL, NULL);
return hRC_temp;
}
const int attribs[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, major,
WGL_CONTEXT_MINOR_VERSION_ARB, minor,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
HGLRC hRC_final = wglCreateContextAttribsARB(hDC, 0, attribs);
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC_temp);
return hRC_final;
}
УМНЫЙ РАНДОМ в С++ (PahomEngine)
// set flag to use random engine e.d random_device to #include <random>
// in true || false
// - true -- enable random_device and std::mt19997
// - false -- disable random_device random use C rand();
void setRandomEngineUsed(bool v) {
bIsRandomEngineUsed = v;
//std::cout << " (random_engine) enabled: " << (bIsRandomEngineUsed ? "true\n" : "false\n");
}
// random engine func
// use: PahomEngine->math->random<type>(max_value,isCached);
// sample:
// int64_t i64ValueRandom = PahomEngine->math->random<int64_t>(255,false);
template <typename Tm>
Tm random(Tm value_max, bool bIsUseCachedRandom = false) {
if(bIsRandomEngineUsed)
{
if (!bIsUseCachedRandom)
{
std::random_device rd_no_cached;
std::mt19937 gen_no_cached(rd_no_cached());
if constexpr (std::is_floating_point_v<Tm>) {
std::uniform_real_distribution<Tm> dist(0, value_max);
return dist(gen_no_cached);
}
else {
std::uniform_int_distribution<Tm> dist(0, value_max);
return dist(gen_no_cached);
}
}
else {
gen.seed(rd());
if constexpr (std::is_floating_point_v<Tm>) {
std::uniform_real_distribution<Tm> dist(0, value_max);
return dist(gen);
}
else {
std::uniform_int_distribution<Tm> dist(0, value_max);
return dist(gen);
}
}
}
else {
return static_cast<Tm>(rand() % (int)value_max);
}
}
#include <format>
#include <stdint.h>
#include <chrono>
#include <vector>
#include <thread>
#include <iostream>
#include <print>
#include <atomic>
#include <random>
int call = 0;
std::atomic <int64_t> size_out = 0;
int thread_id = 0;
struct _rand {
std::mt19937_64 mt;
_rand() {
std::random_device rd;
mt.seed(rd());
}
template<typename T>
T random(T min, T max) {
std::uniform_int_distribution<std::int64_t> dist(min, max);
return dist(mt);
}
};
_rand mtrd;
void generate_password(int64_t size) {
std::string sMask = "qwertyuiopasdfghjklzxcvbnm1234567890";
std::string sOutPassword = "";
// gen
for (int64_t fillChars = 0; fillChars < size; fillChars++) {
sOutPassword += sMask[mtrd.random<int>(0,sMask.size())];
size_out.fetch_add(sOutPassword.size(), std::memory_order_relaxed);
}
}
void bench(int64_t size) {
auto in = std::chrono::high_resolution_clock::now();
std::vector<std::jthread> jthreads;
jthreads.reserve(std::jthread::hardware_concurrency());
for (int i = 0; i < std::jthread::hardware_concurrency(); i++) {
jthreads.emplace_back([=] {
generate_password(size / std::jthread::hardware_concurrency());
});
if (jthreads[i].joinable()) {
thread_id = jthreads[i].get_id()._Get_underlying_id();
std::print("thread ({}) :: ({}) size: ({})\n", (std::to_string(call).size() < 2 ? std::format("0{}", call) : std::to_string(call)), thread_id, size_out.load());
call++;
}
if (call >= std::jthread::hardware_concurrency()) {
auto out = std::chrono::high_resolution_clock::now();
std::cout << "----------------------\n out time : " << std::chrono::duration_cast<std::chrono::nanoseconds>(out - in).count() << " ns\n";
}
}
}
int main(int argc, char** argv) {
int64_t i64MaxSize = (argc < 2 ? 10000000 : std::stoll(argv[1]));
if (argc < 2) {
std::print("argv[1] empty!\nset default size_buffer={}\n", i64MaxSize);
}
else {
std::print("size_buffer={}\n", i64MaxSize);
}
uint32_t u32MaxThreads = std::jthread::hardware_concurrency();
std::print("--------------------------------------\n");
std::print(" \n");
std::print(" CPU Bench by HCPP \n");
std::print(" max_cpu:{} size:{} \n", u32MaxThreads,i64MaxSize);
std::print("--------------------------------------\n");
bench(i64MaxSize);
}
многопоточный бенчмарк кроссплатформенный
windows
создать проект консольный и скопировать код
и включить релиз и С++23 и x64
Linux/ mac os
clang++ -std=c++23 bench_cpu.cpp -o ./cpu_bench
использование
bench.exe (size)
bench size
🔥1
Главная ошибка новичков при работе с массивами это выход за границу массива так как используют std::size();
const int int_array [] = {0,1,2,3,4,5,6,7,8,9};
и обычно пишут
size_t int_array_size = std::size(int_array);
но std::size вернет 10 и если захочешь использовать в логике например
for(int a = 0 ; a < array_size;a++){
std::print("i: {}\n",int_array[a]);
}
то ты выйдешь за границы массива потому то массив начинается от 0
а нужно просто добавить
const int int_array [] = {0,1,2,3,4,5,6,7,8,9};
и обычно пишут
size_t int_array_size = std::size(int_array) - 1;
for(int a = 0 ; a < array_size;a++){
std::print("i: {}\n",int_array[a]);
}
и тогда все сработает правильно
пример
#include <print>
#include <stdint.h>
const int arr[10] = {0,1,2,3,4,5,6,7,8,9};
void bad(){
for(int a = 0; a < std::size(arr);a++){
std::print("i: {}\n",arr[a]);
}
void good(){
for(int a = 0; a < std::size(arr) - 1;a++){
std::print("i: {}\n",arr[a]);
}
int main(){
good(); // выведет от 0 до 9
bad() выведет от 0 до 9 и упадет приложение
}
🔥1
создаем свой ping (Windows/Linux)
net.hpp
main.cpp
net.hpp
#pragma once
#include <iostream>
#include <vector>
#include <cstring>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <thread>
#include <format>
#include <atomic>
#include "io.hpp" // если используете C++23 то отключите просто у меня свой print
#include <mutex>
#include <chrono>
#include "hostname.hpp"
#pragma comment(lib,"ws2_32.lib")
std::mutex net_mt;
struct net {
const char* target_ip = "142.251.1.102";
int target_port = 443;
size_t PACKET_SIZE = 64;
SOCKET sock = INVALID_SOCKET;
sockaddr_in addr;
int64_t max_iteration = 10;
int success = 0, fall = 0, max_packets = 0;
bool bMultiThread = false;
std::string out_ping_str = "";
int64_t i64MaxThreads = std::jthread::hardware_concurrency();
net() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
print(" WSAStartup failed\n");
}
}
void sendDeep() {
setlocale(LC_ALL, "rus");
success = 0; fall = 0;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
print(" Socket creation failed\n");
return;
}
else {
print(" socket created\n");
}
addr.sin_family = AF_INET;
addr.sin_port = htons(target_port);
addr.sin_addr.s_addr = inet_addr(target_ip);
print(" Connecting to [{}]...\n", target_ip);
if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
std::vector<char> buf(PACKET_SIZE, 'X');
for (int64_t count = 0; count < max_iteration; count++) {
SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
auto in_ping = std::chrono::high_resolution_clock::now();
if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
int sentBytes = send(s, buf.data(), (int)buf.size(), 0);
auto out_ping = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(out_ping - in_ping).count();
print(" {} [{}] Отправлен пакет: {} ms\n", count, target_ip, duration);
success++;
closesocket(s);
}
else {
print(" {} [{}] Ошибка подключения\n", count, target_ip);
fall++;
closesocket(s);
}
}
print(" [{}] Сводка: Отправлено {}/{} ping : {}\n", target_ip, success, max_iteration, out_ping_str);
closesocket(sock);
}
else {
int err = WSAGetLastError();
print(" [{}:{}] Connection Error! Code: {}\n", target_ip, target_port, err);
std::cout << " Пока не поддерживаем пинг по URL но вот айпи вот айпи ниже";
print("({}) ->( {} )", target_ip, getIPFromUrl(target_ip));
}
}
~net() {
WSACleanup();
print(" WSACleanup()\n");
}
};
main.cpp
#include "ping.hpp"
struct PING_DATA {
std::string usage_string = R"(
Ошибка команды!
Использование:
ping.exe <флаг> <ip или url> <порт> <размер пакета> <количество пакетов>
-----------------------------------------------------------------
Пример:
ping.exe -host "http://google.com" 80 64 4
| 0 || 1 || 2| 3|4|
0 - Флаг (-ip - для теста по IP , -host - для теста по url
1 - Адрес
2 - Порт
3 - размер пакета
4 - количество пакетов
-------------------------------------------------------------------
created by HCPP20334 | Writtein C++20 Win10SDK
)";
};
std::unique_ptr<PING_DATA> ping = std::make_unique<PING_DATA>();
std::unique_ptr<net>net_ptr = std::make_unique<net>();
std::string hostname_and_ip_str,flag_ping_to;
int main(int argc, char** argv) {
setlocale(LC_ALL, "rus");
if (argc < 2) {
std::cout << ping->usage_string;
}
else {
// flag_ping_to = std::string(reinterpret_cast<const char*>((argv[2])));
print("ping by HCPP20334 | Writtein to C++20\n----------------------\n IP:{} | PORT:{} | MAX_ITERATION:{} | PACKET_SIZE:{}\n", (const char*)argv[1], std::stoi(argv[2]), std::stoi(argv[4]), std::stoll(argv[3]));
hostname_and_ip_str = std::string(reinterpret_cast<const char*>((argv[1])));
net_ptr->target_ip = hostname_and_ip_str.c_str();
net_ptr->target_port = (std::stoi(argv[2]));
net_ptr->PACKET_SIZE = (std::stoll(argv[3]));
net_ptr->max_iteration = (std::stoi(argv[4]));
net_ptr->sendDeep();
}
}
ping.hpp
#pragma once
#include <iostream>
#include <string>
#include <stdint.h>
#include <memory>
#include "net.hpp"
ВОТ свой принт
std::mutex deepPayloadMt;
std::string print_data;
template <class... Tm>
void print(const std::format_string<Tm...> _Fmt, Tm&&... _Args) {
std::lock_guard<std::mutex> lock(deepPayloadMt);
std::string_view out_buffer = _STD vformat(_Fmt.get(), _STD make_format_args(_Args...));
std::cout << out_buffer.data();
}
требования С++20 или С++23
Потоки в С++
например
std::jthread thread_0;
thread_0 = std::jthread([&]{
//твой код
});
std::jthread::hardware_concurrency() //получает количество потоков в процессоре
thread_0.joinable()// возвращает true если поток активен , false если не активен
например
#include <print>
#include <atomic>
#include <stdint.h>
#include <chrono>
#include <thread>
std::atomic<int64_t> counter_big = 0;
std::jthread thread;
int main(){
thread = std::jthread([&]{
while(true){
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter_big.fetch_add(1);
if(counter_big.load() >= 100){counter_big = 100;break;}
std::print("counter: {}",counter_big.load());
}
});
return 0;
}
tui.hpp
7.4 KB
наконец-то закончил работу над TUI!
Теперь она кроссплатформеная полностью
просто добавить рядом с main.cpp
и подключить #include "tui.hpp"
для работы нужен C++20
unix -std=c++20
Windows в настройках проекта Visual Studio C++20 включить
вся документация в исходинике там все расписано как работать с ним
Теперь она кроссплатформеная полностью
просто добавить рядом с main.cpp
и подключить #include "tui.hpp"
для работы нужен C++20
unix -std=c++20
Windows в настройках проекта Visual Studio C++20 включить
вся документация в исходинике там все расписано как работать с ним
// load text to char
void loadFadeText(std::string text) {
for (int c01 = 0; c01 < text.size(); c01++) {
tui->push_color_rgba_v({ 242,0,47 }, { 12, 18, 34 });
std::cout << text[c01];
tui->pop_color_rgba();
}
}
9
#include <iostream>
#include <string>
#include <string_view>
#include <random>
std::string gen_password(std::string_view svMask, int64_t i64Size) {
std::random_device rd;
std::mt19937_64 mt64(rd());
if (svMask.empty()) {
std::cout << "Error: mask empty!!\n";
return "mask_value_error";
} else if (i64Size <= 0) {
std::cout << "Error: password size <= 0;\n";
return "size_null_error";
} else {
std::string sOutput = "";
sOutput.reserve(i64Size);
std::uniform_int_distribution<size_t> dist(0, svMask.size() - 1);
for (int64_t ch = 0; ch < i64Size; ch++) {
int64_t i64Random = dist(mt64);
sOutput += svMask[i64Random];
}
return sOutput;
}
}
int main(){
std::string mask_hash = gen_password("qwertyuiop[]asdfghjkl;'zxcvbnm,./1234567890-=QWERTYUIOP[]ASDFGHJKL;'ZXCVBNM,.",64);
int64_t i64SizePassword = 64;
std::cout <<" Size Password:";
std::cin >> i64SizePassword;
std::cout << gen_password(mask_hash,i64SizePassword);
}
чисто в блокноте написал код генератора паролей лол. Кто проверит?
должен работать и на linux и на Windows
#include <iostream>
#include <string>
#include <stdint.h>
#include <iostream>
#include <string>
#include <stdint.h>
#include <windows.h>
#include <vector>
#include <memory>
#include <chrono>
#include <thread>
int main(){
printf("\n\n\n\n\t\t\tMemTest 0.1 by HCPP20334\n");
uint64_t MB = (1024ULL * 1024ULL);
std::vector<uint64_t> outdata;
int64_t AllocatedMB = 0;
std::cout << "\t\t\tEnter MB:";
std::cin >> AllocatedMB;
if(AllocatedMB < 8){
AllocatedMB = 16;
printf("\t\t\terr: size not <8! set default 8\n");
}
outdata.resize((MB * AllocatedMB) / sizeof(uint64_t));
std::fill(outdata.begin(), outdata.end(), 0);
printf("\t\t\tallocated %lld\n",(MB * AllocatedMB));
printf("\t\t\t mem=%lld | alloc_mem=%lld\n",outdata,AllocatedMB);
int tmax = std::jthread::hardware_concurrency();
std::vector<std::jthread> tc;
tc.resize(tmax);
auto t0 = std::chrono::high_resolution_clock::now();
for(int t = 0; t < tmax;t++){
tc[t] = std::jthread([t,&outdata,tmax] {
for(int64_t a = 0; a < (outdata.size() / tmax); a++){
outdata[(outdata.size() / tmax) * t + a] = 1;
}
});
}
for(int t = 0; t < tmax; t++) {
if(tc[t].joinable()) tc[t].join();
}
auto t1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elp = (t1 - t0);
printf("[->%lld<-]\n",outdata[((0xffff << 16) % outdata.size())]);
std::cout << "\t\t\tTime Writting:" << elp.count() * 1000.0 << "ms\n";
std::cout << "\t\t\tSpeed Filling Buffer:"<< (AllocatedMB / elp.count())<< " MB/s\n";
}
сука std::fill в однопотоке +- также дает лишь при больших данных сосет
простой и быстрый генератор паролей на Си
#include <stdio.h>
#include <stdint.h>
uint64_t xor64(uint64_t i){
uint64_t s = i * 0xaef64829dULL;
s ^= s << 16;
s ^= s << 8;
s ^= s >> 4;
return s;
}
char buf[110] = "";
const char* mask = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890-/:;()₽&@.,?!";
int main(){
for(int a = 0; a < 110; a++){
buf[a] = mask[xor64(a) % strlen(mask)];
}
buf[110] = '\0';
printf("%s", buf);
return 0;
}
/c
#include<stdio.h>
#include<stdint.h>
#include <math.h>
#include <stdlib.h>
const char* Gen() {
const char* key = "";
char Data[17] = {0};
int v1; // edi
int v2; // esi
int v3; // eax
v1 = rand() % 255;
v2 = rand() % 255;
v3 = rand();
sprintf(
Data,
"%02X%02X%02X7C%02X%02X%02X%02X",
v1,
v2 ^ 0x7C,
(uint8_t)~(uint8_t)v1,
v2,
v3 % 255,
(uint8_t)(v3 % 255) ^ 7,
v1 ^ (uint8_t)~(v3 % 255));
key = (const char*)Data;
return key;
}
int main(){
printf("%s",Gen());
}
кусок кода от кейгена для HTTPDEbugger
ПРОВЕРКА ТИПОВ У auto в С++20
HCPP подписаться)
#include <iostream>
#include <string>
#include <stdint.h>
template <typename T>
using Type = std::decay_t<T>;
template <typename T>
constexpr bool isType(auto&& e){
return std::is_same_v<Type<decltype(e)>,T>;
}
int main(){
int intvalue = 0;
int8_t int8value = 0;
int16_t int16value = 0;
int64_t int64value = 0;
float floatvalue = 0.0f;
double doublevalue = 0.0;
long double ldoublevalue = 0.0L;
//
auto &p0 = intvalue;
auto &p1 = int8value;
auto &p2 = int16value;
auto &p3 = int64value;
auto &p4 = floatvalue;
auto &p5 = doublevalue;
auto &p6 = ldoublevalue;
if(isType<int>(p0)) { std::cout << "intvalue=(int)\n";} else { std::cout << "intvalue=(not int)\n";}
if(isType<int8_t>(p1)) { std::cout << "int8value=(int8)\n";} else { std::cout << "int8value=(not int8)\n";}
if(isType<int16_t>(p2)) { std::cout << "int16value=(int16)\n";} else { std::cout << "int16value=(not int16)\n";}
if(isType<int64_t>(p3)) { std::cout << "int64value=(int64)\n";} else { std::cout << "int64value=(not int64)\n";}
if(isType<float>(p4)) { std::cout << "floatvalue=(float)\n";} else { std::cout << "floatvalue=(not float)\n";}
if(isType<double>(p5)) { std::cout << "doublevalue=(double)\n";} else { std::cout << "doublevalue=(not double)\n";}
if(isType<long double>(p6)){ std::cout << "ldoublevalue=(long double)\n";} else { std::cout << "ldouble=(not long double)\n";}
return 0;
}
HCPP подписаться)
#include <iostream>
#include <string>
#include <stdint.h>
#include <fstream>
#include <vector>
#include <algorithm>
std::string sAppAboutString = R"(
-------------------------------------------------
xrayLogParse by hcpp20334
writtein to C++20
MSVC compiler and VS2026
-------------------------------------------------
)";
struct fsm {
void saveFile(std::string data,std::string filename) {
std::ofstream file(filename);
file.write(data.c_str(), data.size());
file.close();
}
std::ofstream log;
void initLogger() {
log = std::ofstream("parse.log");
}
void logger(std::string funcName,std::string data) {
std::cout << "( " << funcName << " ) -> " << data << "\n";
log << "( " << funcName << " ) -> " << data << "\n";
}
void closeLogger() {
log.close();
}
void readLogs(std::vector<std::string>& array) {
std::ifstream logs("logs.txt");
std::string sOutLogsData = "";
if (logs.is_open()) {
logger("readLogs()", "read logs.txt");
while (std::getline(logs, sOutLogsData)) {
logger("readLogs()", "pushed to "+sOutLogsData);
array.push_back(sOutLogsData);
}
}
else {
logger("readLogs()", "error logs.txt not found!");
}
}
fsm() {
std::cout << sAppAboutString;
}
~fsm() {
std::cout << " (fs) cleanup\n";
}
};
fsm* fs = new fsm();
struct str {
void fmt(std::vector<std::string>& vec) {
if (!vec.empty()) {
fs->logger("str->fmt()", "parsing..");
std::vector<std::string> buf;
for (auto& data : vec) {
std::string sln = data;
int64_t i64LastIndex = sln.rfind("connection to ");
if (i64LastIndex != std::string::npos) {
fs->logger("str->fmt()", "finded " + std::to_string(i64LastIndex));
std::string sRaw = sln.substr(i64LastIndex + 14);
buf.push_back(sRaw);
}
}
std::sort(buf.begin(), buf.end());
buf.erase(std::unique(buf.begin(), buf.end()), buf.end());
vec = std::move(buf);
buf.clear();
}
else {
fs->logger("str->fmt()", "vec empty!");
}
}
void saveToOutput(auto& vec) {
std::string sFmtStr = "";
for (auto& s : vec) {
sFmtStr += s + "\n";
}
fs->saveFile(sFmtStr, "output.txt");
}
void CleanupVec(auto& vec) {
if (!vec.empty()) {
vec.clear();
}
}
};
str* strf = new str();
int main() {
std::vector <std::string> vLogs;
fs->initLogger(); // init logger
fs->readLogs(vLogs); // read logs.txt
strf->fmt(vLogs); // fmt string
strf->saveToOutput(vLogs); // save output.txt
fs->closeLogger(); // close logger
strf->CleanupVec(vLogs);
delete fs; // delete fs
delete strf;// delete strf
}
компактный и кроссплатформенный парсер логов xray в throne
// logger.hpp by HCPP20334 (to PahomEngineGL 1.0.4)
// Easy to Log system lib Writtein to C++20
// support VT100 and 16 bit color mode
// use:
// #include "logger.hpp"
//
// int main(){
// logger console;
// console.send("Hello World",0); // WARN
// console.send("Hello World",1); // INFO
// console.send("Hello World",2); // ERR
// console.send("Hello World",1); // DEBUG
// return 0;
// }