如何在源代码中设置程序执行的优先级
How to set a priority for the execution of the program in source code?
我编写了以下代码,它必须搜索指定长度的字符串中两个数字的所有可能组合:
#include <iostream>
#include <Windows.h>
int main ()
{
using namespace std;
cout<<"Enter length of array"<<endl;
int size;
cin>>size;
int * ps=new int [size];
for (int i=0; i<size; i++)
ps[i]=3;
int k=4;
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
while (k>=0)
{
for (int bi=0; bi<size; bi++)
std::cout<<ps[bi];
std::cout<<std::endl;
int i=size-1;
if (ps[i]==3)
{
ps[i]=4;
continue;
}
if (ps[i]==4)
{
while (ps[i]==4)
{
ps[i]=3;
--i;
}
ps[i]=4;
if (i<k)
k--;
}
}
}
当程序在Windows 7上执行时,我看到CPU的负载只有10-15%,为了使我的代码运行得更快,我决定将程序的优先级更改为High。但是当我这样做时,工作量没有增加,CPU 的负载保持不变。为什么 CPU 负载不会改变?不正确的语句SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
?或者这段代码不能更快地工作?
如果您的 CPU 未满负荷工作,则意味着您的应用程序由于 I/O、睡眠、内存或其他设备吞吐量等原因而无法使用它。
但是,这很可能意味着您的 CPU 具有 2+ 个内核,并且您的应用程序是单线程的。在这种情况下,您必须经历将应用程序平行化的过程,这通常既不简单也不快速。
对于您发布的代码,最耗时的操作实际上是(最有可能)打印结果。删除cout
代码,亲眼看看代码的运行速度有多快。
提高程序的优先级不会有太大帮助。
您需要做的是从计算中删除cout
。存储您的计算并在之后输出它们。
正如其他人所指出的,也可能是您使用多核计算机。无论如何,从计算循环中删除任何输出始终是使用 100% 机器计算能力的第一步,而不是在输出上浪费周期。
std::vector<int> results;
results.reserve(1000); // this should ideally match the number of results you expect
while (k>=0)
{
for (int bi=0; bi<size; bi++){
results.push_back(ps[bi]);
}
int i=size-1;
if (ps[i]==3)
{
ps[i]=4;
continue;
}
if (ps[i]==4)
{
while (ps[i]==4)
{
ps[i]=3;
--i;
}
ps[i]=4;
if (i<k)
k--;
}
}
// now here yuo can output your data
for(auto&& res : results){
cout << res << "n"; // n to not force flush
}
cout << endl; // now force flush
可能发生的情况是,您使用的是多核/多线程机器,并且仅在一个线程上运行,其余的CPU功率只是闲置。 因此,您需要对代码进行多线程处理。 看看提升线程。
相关文章:
- 如何在程序执行时查看Valgrind Massif输出(或其他堆分析器)?
- 如何进行程序执行检查
- 捕获异常后如何退出程序执行
- 在程序执行期间从标准输出重定向到自定义流
- 为什么 C++ openMP 程序执行时间更长
- 从Qt应用程序执行MSI文件
- 应用程序执行器 vs lpsz用户名 ADsOpenObject.
- C++:程序执行时"Not Responding"
- JIT 编译器及其在 C++ 前面加快 .NET 中程序执行速度的好处
- 如何让 c++ 程序执行以响应文件打开
- 防止从其他程序执行库中的函数
- Visual样本存储过程从C 程序执行
- 程序执行因细分故障而停止:11
- 注销侏儒会话时如何从Qt应用程序执行"confirm" gnome会话管理器的对话框(不使用QSessionManager)
- 程序执行基本操作所花费的总时间
- 停止直接执行主应用程序并从第二个应用程序执行它
- 引用变量在下一行程序执行后显示未找到的行为
- C 可以在程序执行过程中移动内存映射的文件(boost :: intercecess)移动
- glLinkProgram() 在程序执行中未定义,即使 glew 报告它存在
- 标准 C++ 程序执行期间的函数调用