// 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>
#include <cmath>
#include <random>
#include <thread>
#include <mutex>
#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";
}
#endif
return 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);
}
#endif
return freq;
}
static std::string get_os_info() {
#ifdef _WIN32
return "Windows";
#elif __linux__
return "Linux";
#elif __APPLE__
return "macOS";
#else
return "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;
// 小延迟避免完全占满CPU
std::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);
}
// 让出CPU
std::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());
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 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;
timer.start();
for (int i = 0; i < iterations; ++i) {
result += i * 3 + 7;
result ^= (i >> 2);
result = (result * 1103515245 + 12345) & 0x7fffffff;
}
timer.stop();
return timer.elapsed_ms();
}
double test_float_ops(int iterations) {
Timer timer;
volatile float result = 1.0f;
timer.start();
for (int i = 1; i < iterations; ++i) {
float x = i * 0.001f;
result = std::sin(x) * std::cos(x) + std::sqrt(x + 1.0f);
result = std::exp(-x * 0.1f) * std::log(x + 1.0f);
}
timer.stop();
return timer.elapsed_ms();
}
double test_double_ops(int iterations) {
Timer timer;
volatile double result = 1.0;
timer.start();
for (int i = 1; i < iterations; ++i) {
double x = i * 0.0001;
result = std::sin(x) * std::cos(x) + std::sqrt(x + 1.0);
result = std::exp(-x * 0.01) * std::log(x + 1.0);
}
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();
for (int i = 0; i < size; ++i) {
for (int k = 0; k < size; ++k) {
double aik = A[i * size + k];
for (int j = 0; j < size; ++j) {
C[i * size + j] += aik * B[k * size + j];
}
}
}
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;
}DEEPSEEK的人机测试
这是 2026年6月27日 存档的第 1 版,不是当前版本。查看当前版本