当前位置: 首页 > news >正文

两个简单示例,轻松干翻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;
}

http://www.mrgr.cn/news/20780.html

相关文章:

  • prompt实用技巧-竞对分析-飞书发布会上多维表和低代码平台原型分析
  • 云计算之大数据(下)
  • 菜鸟入门Docker
  • kubernetes Pod failed to create fsnotify watcher: too many open files
  • IPv4地址学习
  • 各网安上市公司的现金还能撑多久?
  • 霍尼韦尔、书客、米家护眼大路灯怎么样?终极测评对比和护眼灯王者机型
  • 项目实战系列: 家居购项目 第一部分
  • 大家都谈的Scaling Law是什么?
  • 两个长整数字符串求和(不允许使用ES6+)
  • SAP物料分类帐后台配置
  • python 下载excel 添加水印
  • dropdown源码分析 -- ant-design-vue系列
  • LLM 进化分岔口:多模态、成本、代码推理
  • RockyLinux8.9上yum安装redis6
  • python 打包tkinter图标问题
  • vue metamask 获取钱包地址
  • shell脚本编写之函数
  • 目标检测-YOLOv4
  • C 语言内存管理语法全解析(malloc、calloc、free)