两个简单示例,轻松干翻CPU
一、引言
有时候,你会有这样看似“无理”,但是很有必要的需求,在高负载的情况下进行某些极端性能测试。首先,你就得把CPU干到红血状态,不然这极限“鸡能”也看不出来啊。
二、测试代码
2.1 示例一(搞定约70%的CPU占用率)
#include <iostream>
#include <thread>
#include <vector>
#include <cmath>void cpu_hog() {while (true) {// 执行一些计算密集型操作for (volatile int i = 0; i < 1000000; ++i) {// 进行一些复杂的计算double result = std::sqrt(i) * std::log(i + 1);}}
}int main() {std::cout << "Starting CPU hog..." << std::endl;// 启动多个线程以增加 CPU 使用率const int num_threads = std::thread::hardware_concurrency(); // 获取可用的线程数std::vector<std::thread> threads;for (int i = 0; i < num_threads; ++i) {threads.emplace_back(cpu_hog);}// 等待线程完成(实际上不会完成,因为是无限循环)for (auto& thread : threads) {thread.join();}return 0;
}
2.2 示例二 (直接一炮红血,100%占用率)
#include <iostream>
#include <thread>
#include <vector>
#include <random>
#include <atomic>std::atomic<long long> inside_circle(0); // 统计落在圆内的点数void calculate_pi(long long iterations) {std::mt19937 rng(std::random_device{}()); // 随机数生成器std::uniform_real_distribution<double> dist(0.0, 1.0);for (long long i = 0; i < iterations; ++i) {double x = dist(rng);double y = dist(rng);if (x * x + y * y <= 1.0) {inside_circle++;}}
}int main() {const int num_threads = std::thread::hardware_concurrency(); // 获取可用的线程数const long long iterations_per_thread = 100000000; // 每个线程的迭代次数std::vector<std::thread> threads;// 启动多个线程来计算 πfor (int i = 0; i < num_threads; ++i) {threads.emplace_back(calculate_pi, iterations_per_thread);}// 等待所有线程完成for (auto& thread : threads) {thread.join();}// 计算 π 的值double pi = 4.0 * inside_circle / (num_threads * iterations_per_thread);std::cout << "Estimated value of π: " << pi << std::endl;return 0;
}