2

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

#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%,为了让我的代码运行得更快,我决定将我的程序的优先级更改为高。但是当我这样做时,工作并没有增加,CPU 的负载保持不变。为什么CPU负载不变?不正确的说法SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);?或者这段代码不能更快地工作?

4

3 回答 3

4

If your CPU is not working at it's full capacity it means that your application is not capable of using it because of causes like I/O, sleeps, memory or other device throughtput capabilties.

Most probably, however, it means that your CPU has 2+ cores and your application is single-threaded. In this case you have to go through the process of paralellizing your application, which is often neither simple nor fast.

In case of the code you posted, the most time consuming operation is actually (most probably) printing the results. Remove the cout code and see for yourself how fast the code will work.

于 2013-09-06T09:36:55.670 回答
2

Increasing the priority of your programm won't help much.

What you need to do is to remove the cout from your calculations. Store your computations and output them afterwards.

As others have noted it might also be that you use a multi-core machine. Anyway removing any output from your computation loop is always a first step to use 100% of your machines computation power for that and not waste cycles on output.

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
于 2013-09-06T09:37:16.327 回答
1

What's probably happening is you're on a multi-core/multi-thread machine and you're running on only one thread, the rest of the CPU power is just sitting idle. So you'll want to multi-thread your code. Look at boost thread.

于 2013-09-06T09:36:48.467 回答