简体   繁体   中英

Why does this C++ program not use 100% CPU but only 10%

This program isn't using all the cpu power. I was expecting it to take over the cpu and run the code the fastest possible, but it only use 10 max

#include <iostream>

using namespace std;

int main(void) {
    unsigned long long x = 600851475143;
    unsigned long long i = x-1;

    while(i <= x) {
            cout << "\r";
            cout << i;

            if((x % i) == 0) {
                    cout << "\n\n";
                    cout << i;

                    break;
            }

            i--;
    }

    system("pause");
}

it only goes to a max of 10%

The speed is probably limited by the speed of the output device. If you pipe the output to a file on disk, it'll be limited by the disk speed. If you just write to a console, it'll be limited by the speed of the console. Either way, the CPU will rarely be the limit.

Edit: since some people apparently don't quite understand the code, perhaps it's best to simplify it a bit. Let's simplify the loop by leaving out the if statement, leaving just:

unsigned long long x = 600851475143;
unsigned long long i = x-1;

while(i <= x) {
        cout << "\r";
        cout << i;
        i--;
}

So, what this does is start from 600851475143 , count down to 0, then stop when i wraps around to std::numeric_limits<unsigned long long>::max() (typically 2 64 -1).

Now, if we add the if statement back in, we can mostly ignore the body that it controls, but we do also get a remainder operation happening every iteration. Without that, the CPU usage would almost certainly be substantially lower still (though the exact number is likely to depend heavily on the hardware -- eg, if you write the output to a disk, the disk's sustained bandwidth will be the controlling factor).

Because you are making blocking I/O calls via cout. Remove the cout statements and it will consume more cpu.

Whenever a thread is blocked on an I/O operation to complete, including stdout which waits for the console to print, the thread is an blocked state. Hence, no CPU time on that thread until the blocking operation is complete. stdout, the kernel, and the console all provide a little bit of buffering to prevent an I/O block, but eventually a program writing fast enough will exceed the buffering provided.

Note. On Windows, this program (with the cout print statements removed) will only use as a maximum of one core of CPU. If you are on a quad core, it will only consume 25% of CPU as reported on Windows task manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM