zsh2517

Untitled

Feb 12th, 2025
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <chrono>
  3. #include <thread>
  4. #include <atomic>
  5. #include <cmath>
  6.  
  7. class CPUUsageController {
  8. private:
  9.     const double targetUsage;  // 目标 CPU 使用率 (0.0 到 1.0)
  10.     const int cycleTimeMs;     // 每个周期的总时间(毫秒)
  11.     std::atomic<bool> running; // 控制运行状态
  12.  
  13.     // 自旋等待函数,消耗 CPU
  14.     void spinWait(std::chrono::milliseconds duration) {
  15.         auto start = std::chrono::high_resolution_clock::now();
  16.         while (std::chrono::high_resolution_clock::now() - start < duration) {
  17.             // 执行一些计算以防止编译器优化
  18.             volatile double x = std::sin(0.5);
  19.         }
  20.     }
  21.  
  22. public:
  23.     // 简单的 clamp 函数实现
  24.     static double clamp(double value, double low, double high) {
  25.         if (value < low) return low;
  26.         if (value > high) return high;
  27.         return value;
  28.     }
  29.  
  30.     CPUUsageController(double targetUsage = 0.7, int cycleTimeMs = 100)
  31.         : targetUsage(clamp(targetUsage, 0.0, 1.0))
  32.         , cycleTimeMs(cycleTimeMs)
  33.         , running(false) {}
  34.  
  35.     void start() {
  36.         running = true;
  37.         while (running) {
  38.             // 计算本周期内需要消耗 CPU 的时间
  39.             int busyTimeMs = static_cast<int>(cycleTimeMs * targetUsage);
  40.             int idleTimeMs = cycleTimeMs - busyTimeMs;
  41.  
  42.             // 消耗 CPU
  43.             spinWait(std::chrono::milliseconds(busyTimeMs));
  44.  
  45.             // 休眠
  46.             if (idleTimeMs > 0) {
  47.                 std::this_thread::sleep_for(std::chrono::milliseconds(idleTimeMs));
  48.             }
  49.         }
  50.     }
  51.  
  52.     void stop() {
  53.         running = false;
  54.     }
  55. };
  56.  
  57. int main(int argc, char* argv[]) {
  58.     if (argc != 2) {
  59.         std::cout << "Usage: " << argv[0] << " <target_cpu_usage>\n";
  60.         std::cout << "Example: " << argv[0] << " 0.7\n";
  61.         return 1;
  62.     }
  63.  
  64.     double targetUsage = std::stod(argv[1]);
  65.     std::cout << "Starting CPU usage controller with target usage: "
  66.               << (targetUsage * 100) << "%\n";
  67.  
  68.     CPUUsageController controller(targetUsage);
  69.     controller.start();
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment