Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a simple piece of C++ code consume lots of my Raspberry's CPU?

I'm trying to rewrite my C++ project using multithreading technique to make it consume as much CPU as possible (before it only ran on 1 core). So to test if multithreading could make a piece of C++ code run on many cores, I've tried to write a very simple test below, single-threaded, and another version with multithreading to compare. However, the result I received when I ran them on my Raspberry Pi is that even the usual code also consumed a lot of my CPU and ran on more than 1 core. How is that possible? I think it should run on only 1 core because it's so simple!!

So it confused me because with those results I couldn't prove that using multithreading could make my code run on multiple cores because without using it I get the same result :(

#include <iostream>
#include <thread>
#include <math.h>
//#include <mutex>

using namespace std;
//mutex mtx;


int pl(int a){
    return a +=35;
}



int main(int argc, char *argv\[\])
{

    int num = 20;
    while(1){
        int ai = pl(num);
        printf("result num is %d\n", ai);
    }

    cout << "Main: program completed" << endl;
    return 0;
}

CPU usage: enter image description here

like image 467
hoango27 Avatar asked Nov 18 '22 01:11

hoango27


1 Answers

After reading all you guys' comments i've searched for kworker and figure out it mostly performs I/O which really consumes lots of my CPU as Mat said. Now after getting I/O (printf) out of the loop everything seems ok, run on only 1 core, thank everyone so much for helping me!

like image 80
hoango27 Avatar answered Dec 18 '22 00:12

hoango27