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 work
  vector<thread> tds;
  for (size_t i = 0; i < num; ++i) {
    tds.emplace_back(work, percentage);
  }
  tds[0].join();
}

参考

https://github.com/mightbxg/DummyWorker

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橘色的喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值