正文
增加 93 行删除 390 行
123456789104 行未改动151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702713 行未改动2752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163176 行未改动3243253263273283293303316 行未改动3383393403413423433443456 行未改动3523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843858 行未改动394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599```cpp// cpu_benchmark_fixed.cpp// 修复Windows编译错误的CPU性能测试程序// 编译:// Linux: g++ -O2 -std=c++11 -pthread cpu_benchmark_fixed.cpp -o cpu_benchmark// Windows: g++ -O2 -std=c++11 -pthread cpu_benchmark_fixed.cpp -o cpu_benchmark.exe#include <iostream>#include <chrono>#include <vector>4 行未改动#include <fstream>#include <iomanip>#include <algorithm>#include <numeric>#include <cstring>#include <atomic>#include <functional>#include <cstdlib>// 条件包含Windows头文件#ifdef _WIN32#include <windows.h>#include <psapi.h>#endif// ==================== 配置参数 ====================namespace Config {const int REPEAT_COUNT = 30;const int ITERATIONS = 100000000;const int WARMUP_ITERATIONS = 150000000;const int WARMUP_ROUNDS = 5;const int MATRIX_SIZE = 512;const int FLOPS_ITERATIONS = 50000000;const int WARMUP_COOLDOWN_MS = 100;}// ==================== CPU信息获取 ====================class CPUInfo {public:static int get_core_count() {return std::thread::hardware_concurrency();}static std::string get_cpu_model() {std::string model = "Unknown";#ifdef __linux__FILE* fp = popen("grep 'model name' /proc/cpuinfo | head -1 | cut -d':' -f2", "r");if (fp) {char buffer[256];if (fgets(buffer, sizeof(buffer), fp)) {model = buffer;model.erase(0, model.find_first_not_of(" \t\n\r"));model.erase(model.find_last_not_of(" \t\n\r") + 1);}pclose(fp);}#elif _WIN32// Windows下获取CPU信息HKEY hKey;char buffer[256];DWORD bufferSize = sizeof(buffer);if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",0, KEY_READ, &hKey) == ERROR_SUCCESS) {if (RegQueryValueExA(hKey, "ProcessorNameString", nullptr,nullptr, (LPBYTE)buffer, &bufferSize) == ERROR_SUCCESS) {model = buffer;}RegCloseKey(hKey);}if (model == "Unknown" || model.empty()) {model = "Windows System";}#endifreturn model;}static std::string get_frequency() {std::string freq = "Unknown";#ifdef __linux__FILE* fp = popen("grep 'MHz' /proc/cpuinfo | head -1 | cut -d':' -f2 | xargs", "r");if (fp) {char buffer[256];if (fgets(buffer, sizeof(buffer), fp)) {freq = buffer;freq.erase(freq.find_last_not_of(" \t\n\r") + 1);freq += " MHz";}pclose(fp);}#elif _WIN32// Windows下获取CPU频率HKEY hKey;DWORD value;DWORD bufferSize = sizeof(value);if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",0, KEY_READ, &hKey) == ERROR_SUCCESS) {if (RegQueryValueExA(hKey, "~MHz", nullptr,nullptr, (LPBYTE)&value, &bufferSize) == ERROR_SUCCESS) {freq = std::to_string(value) + " MHz";}RegCloseKey(hKey);}#endifreturn freq;}static std::string get_os_info() {#ifdef _WIN32return "Windows";#elif __linux__return "Linux";#elif __APPLE__return "macOS";#elsereturn "Unknown OS";#endif}};// ==================== 性能测量工具 ====================class Timer {public:void start() {m_start = std::chrono::high_resolution_clock::now();}void stop() {m_end = std::chrono::high_resolution_clock::now();}double elapsed_ms() const {return std::chrono::duration<double, std::milli>(m_end - m_start).count();}double elapsed_us() const {return std::chrono::duration<double, std::micro>(m_end - m_start).count();}private:std::chrono::high_resolution_clock::time_point m_start, m_end;};// ==================== CPU预热管理器 ====================class CPUWarmup {private:int m_core_count;std::vector<std::thread> m_workers;std::atomic<bool> m_running;public:CPUWarmup() : m_core_count(CPUInfo::get_core_count()), m_running(true) {if (m_core_count <= 0) m_core_count = 1;}// 1. 空转预热static void idle_warmup(int duration_ms) {Timer timer;timer.start();volatile int dummy = 0;while (timer.elapsed_ms() < duration_ms) {dummy += 1;// 小延迟避免完全占满CPUstd::this_thread::sleep_for(std::chrono::microseconds(1));}}// 2. 全核心负载预热void load_warmup(int duration_ms) {m_running = true;int cores = std::min(m_core_count, 8); // 限制最多8个线程避免系统卡顿for (int i = 0; i < cores; ++i) {m_workers.emplace_back([this]() {volatile int x = 0;while (m_running.load(std::memory_order_relaxed)) {// 高强度混合运算for (int j = 0; j < 5000; ++j) {x += j * 3 + 7;x ^= (j >> 2);double d = std::sin((double)x) * std::cos((double)x) + std::sqrt((double)std::abs(x) + 1.0);x = (int)(d * 100);}// 让出CPUstd::this_thread::yield();}});}std::this_thread::sleep_for(std::chrono::milliseconds(duration_ms));// 停止工作线程m_running = false;for (auto& t : m_workers) {if (t.joinable()) t.join();}m_workers.clear();}// 3. 温度稳定static void thermal_stabilize(int duration_ms) {volatile int x = 0;Timer timer;timer.start();while (timer.elapsed_ms() < duration_ms) {for (int i = 0; i < 1000; ++i) {x = x * 1103515245 + 12345;double d = std::sin((double)x) * std::cos((double)x);x = (int)(d * 1000);}}}// 完整的预热流程static void full_warmup() {std::cout << "\n" << std::string(50, '=') << "\n";std::cout << " CPU预热流程\n";std::cout << std::string(50, '=') << "\n";CPUWarmup warmup;std::cout << " 阶段1: 唤醒CPU (2秒)...\n";idle_warmup(2000);std::cout << " 阶段2: 全核心负载预热 (3秒)...\n";warmup.load_warmup(3000);std::cout << " 阶段3: 热稳定 (2秒)...\n";thermal_stabilize(2000);std::cout << " 阶段4: 冷却稳定 (0.5秒)...\n";std::this_thread::sleep_for(std::chrono::milliseconds(500));std::cout << " 预热完成!\n";}};// ==================== 测试套件 ====================class CPUBenchmark {private:std::vector<double> m_results;std::mutex m_mutex;std::string m_test_name;public:CPUBenchmark(const std::string& name) : m_test_name(name) {}void add_result(double time_ms) {std::lock_guard<std::mutex> lock(m_mutex);m_results.push_back(time_ms);}void clear() { m_results.clear(); }void print_statistics() const {if (m_results.empty()) {std::cout << " 无数据\n";return;}auto sorted = m_results;std::sort(sorted.begin(), sorted.end());3 行未改动double sq_sum = 0.0;for (double v : sorted) sq_sum += (v - mean) * (v - mean);double stddev = std::sqrt(sq_sum / sorted.size());double z_score = 1.96;double ci_half = z_score * stddev / std::sqrt(sorted.size());std::cout << " 实验结果 (ms):\n";std::cout << " 最小值: " << std::fixed << std::setprecision(3) << sorted.front() << "\n";std::cout << " 最大值: " << std::fixed << std::setprecision(3) << sorted.back() << "\n";std::cout << " 平均值: " << std::fixed << std::setprecision(3) << mean << "\n";std::cout << " 标准差: " << std::fixed << std::setprecision(3) << stddev << "\n";std::cout << " 中位数: " << std::fixed << std::setprecision(3) << sorted[sorted.size()/2] << "\n";std::cout << " 95%置信区间: [" << (mean - ci_half) << ", " << (mean + ci_half) << "]\n";double cv = (stddev / mean) * 100.0;std::cout << " 变异系数: " << std::fixed << std::setprecision(2) << cv << "%";if (cv < 2.0) std::cout << " ★ 非常稳定";else if (cv < 5.0) std::cout << " ✓ 较稳定";else std::cout << " ⚠ 波动较大";std::cout << "\n";}const std::vector<double>& get_results() const { return m_results; }};// ==================== 测试函数 ====================template<typename Func>double run_with_warmup(Func test_func, int warmup_iterations, int test_iterations) {volatile int warmup_dummy = 0;for (int i = 0; i < warmup_iterations; ++i) {warmup_dummy += i;}std::this_thread::sleep_for(std::chrono::milliseconds(Config::WARMUP_COOLDOWN_MS));return test_func(test_iterations);}double test_integer_ops(int iterations) {Timer timer;volatile int result = 0;6 行未改动timer.stop();return timer.elapsed_ms();}double test_float_ops(int iterations) {Timer timer;volatile float result = 1.0f;6 行未改动timer.stop();return timer.elapsed_ms();}double test_double_ops(int iterations) {Timer timer;volatile double result = 1.0;6 行未改动timer.stop();return timer.elapsed_ms();}double test_memory_bandwidth(int iterations) {const int size = 64 * 1024 * 1024 / sizeof(int);std::vector<int> data(size);volatile long long sum = 0;for (int i = 0; i < size; ++i) data[i] = i;Timer timer;timer.start();for (int iter = 0; iter < std::max(1, iterations / 10000); ++iter) {for (int i = 0; i < size; ++i) {sum += data[i];}}timer.stop();return timer.elapsed_ms();}double test_matrix_multiply(int size) {std::vector<double> A(size * size);std::vector<double> B(size * size);std::vector<double> C(size * size, 0.0);for (int i = 0; i < size * size; ++i) {A[i] = i * 0.1;B[i] = i * 0.01;}Timer timer;timer.start();8 行未改动timer.stop();return timer.elapsed_ms();}double test_prime_calculation(int max_number) {std::vector<bool> is_prime(max_number + 1, true);is_prime[0] = is_prime[1] = false;Timer timer;timer.start();for (int i = 2; i * i <= max_number; ++i) {if (is_prime[i]) {for (int j = i * i; j <= max_number; j += i) {is_prime[j] = false;}}}timer.stop();return timer.elapsed_ms();}double test_sorting(int size) {std::vector<int> data(size);std::random_device rd;std::mt19937 gen(rd());Timer timer;timer.start();for (int iter = 0; iter < 5; ++iter) {for (int i = 0; i < size; ++i) {data[i] = gen() % 1000000;}std::sort(data.begin(), data.end());}timer.stop();return timer.elapsed_ms();}// ==================== 实验控制器 ====================class ExperimentController {private:std::string m_output_file;std::vector<std::pair<std::string, std::vector<double>>> m_all_results;public:ExperimentController(const std::string& file = "benchmark_results.csv"): m_output_file(file) {}void run_experiment() {print_header();CPUWarmup::full_warmup();std::cout << "\n" << std::string(50, '=') << "\n";std::cout << " 开始性能测试\n";std::cout << std::string(50, '=') << "\n";std::vector<std::pair<std::string, std::function<double()>>> tests = {{"整数运算", [&]() {return run_with_warmup(test_integer_ops,Config::WARMUP_ITERATIONS, Config::ITERATIONS);}},{"单精度浮点", [&]() {return run_with_warmup(test_float_ops,Config::WARMUP_ITERATIONS / 2, Config::FLOPS_ITERATIONS / 2);}},{"双精度浮点", [&]() {return run_with_warmup(test_double_ops,Config::WARMUP_ITERATIONS / 2, Config::FLOPS_ITERATIONS / 2);}},{"内存带宽", [&]() {return run_with_warmup(test_memory_bandwidth,10, 50);}},{"矩阵乘法", [&]() {return run_with_warmup(test_matrix_multiply,128, Config::MATRIX_SIZE);}},{"素数计算", [&]() {return run_with_warmup(test_prime_calculation,500000, 1000000);}},{"排序算法", [&]() {return run_with_warmup(test_sorting,50000, 100000);}},};for (auto& test : tests) {run_single_test(test.first, test.second);}export_results();print_footer();}void run_single_test(const std::string& name, std::function<double()> test_func) {std::cout << "\n测试: " << name << "\n";std::cout << std::string(40, '-') << "\n";CPUBenchmark benchmark(name);std::cout << " 针对性预热...\n";for (int i = 0; i < 3; ++i) {test_func();}std::cout << " 正式测试 (" << Config::REPEAT_COUNT << " 次)...\n";for (int i = 0; i < Config::REPEAT_COUNT; ++i) {double result = test_func();benchmark.add_result(result);int progress = (i + 1) * 50 / Config::REPEAT_COUNT;std::cout << "\r 进度: [" << std::string(progress, '#')<< std::string(50 - progress, ' ')<< "] " << (i+1) << "/" << Config::REPEAT_COUNT << " "<< std::fixed << std::setprecision(2) << result << " ms";std::cout.flush();std::this_thread::sleep_for(std::chrono::milliseconds(10));}std::cout << "\n";benchmark.print_statistics();m_all_results.push_back({name, benchmark.get_results()});}void print_header() {std::cout << "\n" << std::string(60, '#') << "\n";std::cout << " CPU性能基准测试 v2.0\n";std::cout << std::string(60, '#') << "\n";std::cout << "操作系统: " << CPUInfo::get_os_info() << "\n";std::cout << "CPU: " << CPUInfo::get_cpu_model() << "\n";std::cout << "核心数: " << CPUInfo::get_core_count() << "\n";std::cout << "频率: " << CPUInfo::get_frequency() << "\n";std::cout << "重复次数: " << Config::REPEAT_COUNT << "\n";std::cout << "迭代次数: " << Config::ITERATIONS << "\n";}void print_footer() {std::cout << "\n" << std::string(60, '#') << "\n";std::cout << " 测试完成!\n";std::cout << " 结果已保存至: " << m_output_file << "\n";std::cout << std::string(60, '#') << "\n";}void export_results() {std::ofstream file(m_output_file);if (!file.is_open()) {std::cerr << "无法打开输出文件: " << m_output_file << "\n";return;}file << "测试名称,最小值,最大值,平均值,标准差,中位数,变异系数(%),样本数\n";for (const auto& result : m_all_results) {const auto& name = result.first;const auto& data = result.second;if (data.empty()) continue;auto sorted = data;std::sort(sorted.begin(), sorted.end());double sum = std::accumulate(sorted.begin(), sorted.end(), 0.0);double mean = sum / sorted.size();double sq_sum = 0.0;for (double v : sorted) sq_sum += (v - mean) * (v - mean);double stddev = std::sqrt(sq_sum / sorted.size());double cv = (stddev / mean) * 100.0;file << name << ","<< std::fixed << std::setprecision(3)<< sorted.front() << ","<< sorted.back() << ","<< mean << ","<< stddev << ","<< sorted[sorted.size()/2] << ","<< cv << ","<< data.size() << "\n";}file.close();std::cout << "结果已导出\n";}};// ==================== 主函数 ====================int main(int argc, char* argv[]) {std::string output_file = "benchmark_results.csv";if (argc > 1) {output_file = argv[1];}try {ExperimentController controller(output_file);controller.run_experiment();} catch (const std::exception& e) {std::cerr << "错误: " << e.what() << "\n";return 1;}return 0;}```123456784 行未改动1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586873 行未改动9192939495969798991001011021031041051061071081091101111121131141151166 行未改动1231241251261271281291301316 行未改动1381391401411421431441451466 行未改动1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881898 行未改动198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302```cpp// cpu_benchmark_no_warmup.cpp// 简单直接的CPU性能测试(无预热,不卡顿)// 编译: g++ -O2 -std=c++11 -pthread cpu_benchmark_no_warmup.cpp -o cpu_benchmark.exe#include <iostream>#include <chrono>#include <vector>4 行未改动#include <fstream>#include <iomanip>#include <algorithm>#include <numeric>#include <atomic>#include <functional>#include <windows.h>// ==================== 配置参数 ====================namespace Config {const int REPEAT_COUNT = 20; // 重复次数const int ITERATIONS = 50000000; // 迭代次数const int MATRIX_SIZE = 256; // 矩阵大小const int FLOPS_ITERATIONS = 20000000;}// ==================== CPU信息 ====================class CPUInfo {public:static int get_core_count() {SYSTEM_INFO sysInfo;GetSystemInfo(&sysInfo);return sysInfo.dwNumberOfProcessors;}static std::string get_cpu_model() {std::string model = "Unknown";HKEY hKey;char buffer[256];DWORD bufferSize = sizeof(buffer);if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",0, KEY_READ, &hKey) == ERROR_SUCCESS) {if (RegQueryValueExA(hKey, "ProcessorNameString", nullptr,nullptr, (LPBYTE)buffer, &bufferSize) == ERROR_SUCCESS) {model = buffer;while (!model.empty() && model.back() == ' ') model.pop_back();}RegCloseKey(hKey);}return model;}};// ==================== 计时器 ====================class Timer {public:void start() { m_start = std::chrono::high_resolution_clock::now(); }void stop() { m_end = std::chrono::high_resolution_clock::now(); }double elapsed_ms() const {return std::chrono::duration<double, std::milli>(m_end - m_start).count();}private:std::chrono::high_resolution_clock::time_point m_start, m_end;};// ==================== 测试套件 ====================class CPUBenchmark {private:std::vector<double> m_results;std::mutex m_mutex;public:void add_result(double time_ms) {std::lock_guard<std::mutex> lock(m_mutex);m_results.push_back(time_ms);}void print_statistics(const std::string& name) const {if (m_results.empty()) return;auto sorted = m_results;std::sort(sorted.begin(), sorted.end());3 行未改动double sq_sum = 0.0;for (double v : sorted) sq_sum += (v - mean) * (v - mean);double stddev = std::sqrt(sq_sum / sorted.size());double cv = (stddev / mean) * 100.0;std::cout << "\n" << name << ":\n";std::cout << " 平均: " << std::fixed << std::setprecision(2) << mean << " ms\n";std::cout << " 最小: " << sorted.front() << " ms\n";std::cout << " 最大: " << sorted.back() << " ms\n";std::cout << " 标准差: " << stddev << " ms\n";std::cout << " 变异系数: " << cv << "%";if (cv < 3.0) std::cout << " ★";std::cout << "\n";}const std::vector<double>& get_results() const { return m_results; }};// ==================== 测试函数 ====================// 1. 整数运算double test_integer_ops(int iterations) {Timer timer;volatile int result = 0;6 行未改动timer.stop();return timer.elapsed_ms();}// 2. 浮点运算double test_float_ops(int iterations) {Timer timer;volatile float result = 1.0f;6 行未改动timer.stop();return timer.elapsed_ms();}// 3. 双精度浮点double test_double_ops(int iterations) {Timer timer;volatile double result = 1.0;6 行未改动timer.stop();return timer.elapsed_ms();}// 4. 内存带宽double test_memory_bandwidth() {const int size = 20 * 1024 * 1024 / sizeof(int);std::vector<int> data(size);volatile long long sum = 0;for (int i = 0; i < size; ++i) data[i] = i;Timer timer;timer.start();for (int iter = 0; iter < 3; ++iter) {for (int i = 0; i < size; ++i) {sum += data[i];}}timer.stop();return timer.elapsed_ms();}// 5. 矩阵乘法double test_matrix_multiply() {const int size = Config::MATRIX_SIZE;std::vector<double> A(size * size);std::vector<double> B(size * size);std::vector<double> C(size * size, 0.0);for (int i = 0; i < size * size; ++i) {A[i] = (i % size) * 0.1;B[i] = (i / size) * 0.01;}Timer timer;timer.start();8 行未改动timer.stop();return timer.elapsed_ms();}// 6. 素数计算double test_prime_calculation() {const int max_num = 500000;std::vector<bool> is_prime(max_num + 1, true);is_prime[0] = is_prime[1] = false;Timer timer;timer.start();for (int i = 2; i * i <= max_num; ++i) {if (is_prime[i]) {for (int j = i * i; j <= max_num; j += i) {is_prime[j] = false;}}}timer.stop();return timer.elapsed_ms();}// 7. 排序double test_sorting() {const int size = 100000;std::vector<int> data(size);std::random_device rd;std::mt19937 gen(rd());Timer timer;timer.start();for (int iter = 0; iter < 3; ++iter) {for (int i = 0; i < size; ++i) {data[i] = gen() % 1000000;}std::sort(data.begin(), data.end());}timer.stop();return timer.elapsed_ms();}// ==================== 主程序 ====================int main() {// 设置控制台编码SetConsoleOutputCP(936);std::cout << "\n" << std::string(60, '=') << "\n";std::cout << " CPU性能测试 (无预热版)\n";std::cout << std::string(60, '=') << "\n";std::cout << "CPU: " << CPUInfo::get_cpu_model() << "\n";std::cout << "核心数: " << CPUInfo::get_core_count() << "\n";std::cout << "重复次数: " << Config::REPEAT_COUNT << "\n";std::cout << std::string(60, '=') << "\n";// 测试配置struct TestConfig {std::string name;std::function<double()> func;};std::vector<TestConfig> tests = {{"整数运算", []() { return test_integer_ops(Config::ITERATIONS); }},{"单精度浮点", []() { return test_float_ops(Config::FLOPS_ITERATIONS); }},{"双精度浮点", []() { return test_double_ops(Config::FLOPS_ITERATIONS); }},{"内存带宽", []() { return test_memory_bandwidth(); }},{"矩阵乘法", []() { return test_matrix_multiply(); }},{"素数计算", []() { return test_prime_calculation(); }},{"排序算法", []() { return test_sorting(); }}};// 运行所有测试for (auto& test : tests) {CPUBenchmark benchmark;std::cout << "\n测试: " << test.name << "\n";std::cout << " 运行 " << Config::REPEAT_COUNT << " 次...\n";for (int i = 0; i < Config::REPEAT_COUNT; ++i) {double result = test.func();benchmark.add_result(result);// 进度条int progress = (i + 1) * 40 / Config::REPEAT_COUNT;std::cout << "\r [" << std::string(progress, '#')<< std::string(40 - progress, ' ')<< "] " << (i+1) << "/" << Config::REPEAT_COUNT<< " " << std::fixed << std::setprecision(2) << result << " ms";std::cout.flush();std::this_thread::sleep_for(std::chrono::milliseconds(5));}std::cout << "\n";benchmark.print_statistics(test.name);}std::cout << "\n" << std::string(60, '=') << "\n";std::cout << "测试完成!\n";std::cout << std::string(60, '=') << "\n";system("pause");return 0;}```