0

I wrote some in c++ and try to execute it on raspberry pi . I noticed a CPU Load of 100 % I then removed bit for bit from the code to see what causes the high load. Now my code looks like the code below (stripped of all functionality ) and it still has 99-100% load. Can someone point me in the right direction ?

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <map>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <cmath>
#include <sys/socket.h>
#include <arpa/inet.h>

using namespace std;

int main(int argc, char* argv[])
{
    // Check command line arguments
    if (argc < 3) {
        cout << "Usage: Test can_name dbc_file" << endl;
        return 1;
    }

// Get can name and dbc file name from command line arguments
    string canName = argv[1];
    string dbcFileName = argv[2];

    while (true) {

    }
    return 0;
}

I tried to strip my code of all funtionality to end up with a basic program that should have very little cpu load

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Markus
  • 319
  • 5
  • 18
  • 7
    `while (true) {}` will consume 100% of a single CPU core. – HolyBlackCat Jan 20 '23 at 12:40
  • 2
    Maybe slow down your while loop iteration? You can sleep the main thread for some milliseconds. – Vahan Jan 20 '23 at 12:41
  • while (true) {} will put the program in a endles loop . The initial program was opening a DBC (Vector CAN definition file ) and parse it . In the while loop i was monitoring CAN bus messages and compute them. As said in the description i removed the code line for line until i had just this basic skeleton left and still can't find what causes the high load . – Markus Jan 20 '23 at 12:45
  • If you take out the `while (true) {}` the high load should go away. – Eljay Jan 20 '23 at 12:50
  • @Markus `while(true)` cause constant load of the CPU as it infintely checks if it is true. If you, as suggested by others, insert a sleep or some form of delay, you should see the CPU usage reduce when the check is not being made – Lars Nielsen Jan 20 '23 at 12:50
  • 1
    Your program exhibits _undefined behavoir_ and its largely pointless to speculate on the performance or correctness of any program which has undefined behavoir. – Mike Vine Jan 20 '23 at 13:37

1 Answers1

1

Try adding a sleep within the loop like

while ( true ) {
    usleep(100000); // sleeps for 100 ms
}
Something Something
  • 3,999
  • 1
  • 6
  • 21