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

dummy_worker C++ 预占用部分比例cpu资源,人为创造cpu资源紧张

背景

有时候为了C++测试程序在cpu资源紧张情况下是否正常,需要人为创造cpu资源紧张

编译方法

g++ -o dummp_worker dummp_worker.cpp -std=c++11 -pthread

使用方法

./dummp_worker 4 0.2

占用4个cpu核的20%比例的cpu资源

源码

// dummp_worker.cpp
#include <cassert>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>using namespace std;
using namespace chrono;void busy_wait(size_t nanosec) {auto t0 = high_resolution_clock::now();while (duration_cast<nanoseconds>(high_resolution_clock::now() - t0).count() < nanosec) {}
}[[noreturn]] void work(float percentage) {assert(percentage >= 0.f && percentage <= 1.f);constexpr float period = 1000000.0f;while (true) {// busy_wait(900000);// this_thread::sleep_for(100000ns);busy_wait(static_cast<size_t>(period * percentage));this_thread::sleep_for(nanoseconds(static_cast<size_t>(period * (1.f - percentage))));}
}int main(int argc, char* argv[]) {if (argc < 3) {cout << "Args: worker_num occupation_rate.\n";return 0;}const int num = stoi(argv[1]);const float percentage = stof(argv[2]);if (num < 1) {cout << "Error: num of workers less than 1.\n";return 0;}if (percentage < 0.f || percentage > 1.f) {cout << "Error: occupation rate should be between [0.0, 1.0].\n";return 0;}cout << "num of workers: " << num << "\n"<< "occupation rate: " << percentage << "\n";// do the workvector<thread> tds;for (size_t i = 0; i < num; ++i) {tds.emplace_back(work, percentage);}tds[0].join();
}

参考

https://github.com/mightbxg/DummyWorker

http://www.lryc.cn/news/344714.html

相关文章:

  • 电脑缺失opencl.dll怎么办,轻松解决opencl.dll的多种方法分享
  • el-select 点击按钮滚动到选择框顶部
  • vue 钩子函数updated什么时候触发
  • 消息队列使用常见问题
  • 常用SQL命令
  • 【neteq】tgcall的调用、neteq的创建及接收侧ReceiveStatisticsImpl统计
  • 使用Python读取las点云,写入las点云,无损坐标精度
  • python开发二
  • 部署JVS服务出现上传文件不可用,问题原因排查。
  • 机器视觉检测为什么是工业生产的刚需?
  • Adobe系列软件安装
  • 【FX110】2024外汇市场中交易量最大的货币对是哪个?
  • leetcode尊享面试100题(549二叉树最长连续序列||,python)
  • C#面试题: 寻找中间值
  • 987: 输出用先序遍历创建的二叉树是否为完全二叉树的判定结果
  • 13:HAL---SPI
  • 微服务---gateway网关
  • HTML4(二)
  • SpringBoot 扩展篇:ConfigFileApplicationListener源码解析
  • 蓝桥杯省三爆改省二,省一到底做错了什么?
  • Unity EventSystem入门
  • 第4章 Vim编辑器与Shell命令脚本
  • javaWeb快速部署到tomcat阿里云服务器
  • [MQTT]Mosquitto的內網連接(intranet)和使用者/密碼權限設置
  • 某盾BLACKBOX逆向关键点
  • 【2024全国青少年信息素养大赛初赛时间以及模拟题】
  • 2024年软件测试最全jmeter做接口压力测试_jmeter接口性能测试_jmeter压测接口(3),【大牛疯狂教学
  • LLM——用于微调预训练大型语言模型(LLM)的GPU内存优化与微调
  • Telnet协议:远程控制的基石
  • 网络工程师必备:静态路由实验指南