簡體   English   中英

有沒有辦法限制 c++ 應用程序使用的 CPU 數量

[英]Is there a way to limit the amount of CPU a c++ application uses

我正在開發一個計算 recaman 序列的程序。 我想計算然后可視化序列中的數千或數百萬個術語。 但是,我注意到它占用了 10% 的 CPU,並且任務管理器說它的電源使用率非常高。 我不想損壞電腦,願意為了電腦的安全犧牲速度。 有沒有辦法限制這個應用程序的 CPU 使用率或電池消耗水平?

這適用於 Windows 10。

//My Function for calculating the sequence
//If it helps, you could look up 'Recaman Sequence' on google

void processSequence(int numberOfTerms) {
    int* terms;
    terms = new int[numberOfTerms];

    terms[0] = 0;
    cout << "Term Number " << 0 << " is: " << 0 << endl;

    int currentTermNumber = 1;
    int lastTerm = 0;
    int largestTerm = 0;

    for (currentTermNumber; currentTermNumber < numberOfTerms; currentTermNumber++) {
        int thisTerm;
        bool termTaken = false;
        for (int j = 0; j < numberOfTerms; j++) {
            if (terms[j] == lastTerm - currentTermNumber) {
                termTaken = true;
            }
        }

        if (!termTaken && lastTerm - currentTermNumber > 0) {
            thisTerm = lastTerm - currentTermNumber;
        }
        else {
            thisTerm = lastTerm + currentTermNumber;
        }

        if (thisTerm > largestTerm) {
            largestTerm = thisTerm;
        }
        lastTerm = thisTerm;

        cout << "Term Number " << currentTermNumber << " is: " << thisTerm << endl;
    };

    cout << "The Largest Term Number Was: " << largestTerm << endl;

    delete[] terms;
}

使用更少 CPU 的最簡單方法是不時休眠一小段時間,例如一毫秒或幾毫秒。 您可以通過調用 Sleep (Windows API) 或 current_thread::sleep (自 C++11 起為標准)來完成此操作。

然而,

  • 100% 使用所有內核時,您永遠不會對計算機造成物理損壞。 無論如何,大多數電子游戲都是如此貪婪。 可能發生的最壞情況是突然關閉並且在接下來的幾分鍾內無法再次打開,以防 CPU 達到極限溫度 (80-100°C)。 這種安全性確實可以防止任何危險和/或不可恢復的事情。
  • 像這樣故意減慢您的程序幾乎沒有意義。 如果您在用戶界面中遇到緩慢,您應該將密集處理移至非 UI 線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM