c++ - 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;
}
解决方案
使用更少 CPU 的最简单方法是不时休眠一小段时间,例如一毫秒或几毫秒。您可以通过调用 Sleep (Windows API) 或 current_thread::sleep (自 C++11 起为标准)来完成此操作。
然而,
- 100% 使用所有内核时,您永远不会对计算机造成物理损坏。无论如何,大多数电子游戏都是如此贪婪。可能发生的最坏情况是突然关闭并且在接下来的几分钟内无法再次打开,以防 CPU 达到极限温度 (80-100°C)。这种安全性确实可以防止任何危险和/或不可恢复的事情。
- 像这样故意减慢您的程序几乎没有意义。如果您在用户界面中遇到缓慢,您应该将密集处理移至非 UI 线程。
推荐阅读
- google-api-python-client - 如何在 Google Talent Solution 中为多个工作调用 batchDelete()?
- html - Safari:在固定选项卡中,带有数据 href 的下载属性不起作用
- xml - JavaFX - 如何定期读取 xml 文件并更新 TableView
- checkbox - Yii2:选中复选框后显示字段/复选框
- java - 分离的实体通过额外的列保持多对多
- apache-kafka - 启动 kafka-gcs 汇合连接器时找不到类 io.confluent.connect.gcs.GcsSinkConnector
- java - java.lang.ClassNotFoundException:javax.persistence.criteria.Selection
- javascript - Vue.js 过渡:使用滑出动画时为高度设置动画
- excel - 如何在字符串中调用单元格值?
- python - 无法安装熊猫 - InsecurePlatformWarning 错误