如何在源代码中设置程序执行的优先级

How to set a priority for the execution of the program in source code?

本文关键字:程序 执行 优先级 设置 源代码      更新时间:2023-10-16

我编写了以下代码,它必须搜索指定长度的字符串中两个数字的所有可能组合:

#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功率只是闲置。 因此,您需要对代码进行多线程处理。 看看提升线程。