AI写的,压力测试代码 (配置差的不建议
2026-08-22 14:03:50
发布于:北京
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
//用于控制线程退出的标志
std::atomic<bool> keep_running(true);
// 工作函数:执行空运算以消耗 CPU
void burn_cpu() {
// volatile 防止编译器优化掉空循环
volatile long long counter = 0;
while (keep_running) {
counter++;
}
}
int main() {
// 获取硬件支持的并发线程数(即逻辑核心数)
unsigned int num_threads = std::thread::hardware_concurrency();
if (num_threads == 0) {
std::cerr << "无法检测核心数,默认使用 4 个线程" << std::endl;
num_threads = 4;
}
std::cout << "检测到 " << num_threads << " 个逻辑核心,正在启动压力测试..." << std::endl;
std::cout << "按 Enter 键停止程序..." << std::endl;
std::vector<std::thread> threads;
threads.reserve(num_threads);
// 为每个核心创建一个线程
for (unsigned int i = 0; i < num_threads; ++i) {
threads.emplace_back(burn_cpu);
}
// 主线程等待用户输入,以便安全退出
std::cin.get();
// 通知所有工作线程停止
keep_running = false;
// 等待所有线程结束
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
std::cout << "压力测试已停止。" << std::endl;
return 0;
}
这里空空如也



















有帮助,赞一个