Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <chrono>
- #include <thread>
- #include <atomic>
- #include <cmath>
- class CPUUsageController {
- private:
- const double targetUsage; // 目标 CPU 使用率 (0.0 到 1.0)
- const int cycleTimeMs; // 每个周期的总时间(毫秒)
- std::atomic<bool> running; // 控制运行状态
- // 自旋等待函数,消耗 CPU
- void spinWait(std::chrono::milliseconds duration) {
- auto start = std::chrono::high_resolution_clock::now();
- while (std::chrono::high_resolution_clock::now() - start < duration) {
- // 执行一些计算以防止编译器优化
- volatile double x = std::sin(0.5);
- }
- }
- public:
- // 简单的 clamp 函数实现
- static double clamp(double value, double low, double high) {
- if (value < low) return low;
- if (value > high) return high;
- return value;
- }
- CPUUsageController(double targetUsage = 0.7, int cycleTimeMs = 100)
- : targetUsage(clamp(targetUsage, 0.0, 1.0))
- , cycleTimeMs(cycleTimeMs)
- , running(false) {}
- void start() {
- running = true;
- while (running) {
- // 计算本周期内需要消耗 CPU 的时间
- int busyTimeMs = static_cast<int>(cycleTimeMs * targetUsage);
- int idleTimeMs = cycleTimeMs - busyTimeMs;
- // 消耗 CPU
- spinWait(std::chrono::milliseconds(busyTimeMs));
- // 休眠
- if (idleTimeMs > 0) {
- std::this_thread::sleep_for(std::chrono::milliseconds(idleTimeMs));
- }
- }
- }
- void stop() {
- running = false;
- }
- };
- int main(int argc, char* argv[]) {
- if (argc != 2) {
- std::cout << "Usage: " << argv[0] << " <target_cpu_usage>\n";
- std::cout << "Example: " << argv[0] << " 0.7\n";
- return 1;
- }
- double targetUsage = std::stod(argv[1]);
- std::cout << "Starting CPU usage controller with target usage: "
- << (targetUsage * 100) << "%\n";
- CPUUsageController controller(targetUsage);
- controller.start();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment