首页 > 解决方案 > Is there a way to limit the amount of CPU a c++ application uses

问题描述

I'm working on a program that calculates the recaman sequence. I want to calculate and then later visualize thousands or millions of terms in the sequence. However, I've noticed that it is taking up 10% of CPU, and the task manager says it has very high power usage. I don't want to damage the computer, and am willing to sacrifice speed for the safety of the computer. Is there a way to limit the CPU usage or battery consumption level of this application?

This is for 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;
}

标签: c++cpu-usage

解决方案


使用更少 CPU 的最简单方法是不时休眠一小段时间,例如一毫秒或几毫秒。您可以通过调用 Sleep (Windows API) 或 current_thread::sleep (自 C++11 起为标准)来完成此操作。

然而,

  • 100% 使用所有内核时,您永远不会对计算机造成物理损坏。无论如何,大多数电子游戏都是如此贪婪。可能发生的最坏情况是突然关闭并且在接下来的几分钟内无法再次打开,以防 CPU 达到极限温度 (80-100°C)。这种安全性确实可以防止任何危险和/或不可恢复的事情。
  • 像这样故意减慢您的程序几乎没有意义。如果您在用户界面中遇到缓慢,您应该将密集处理移至非 UI 线程。

推荐阅读