0

I have a while loop as follows:

while(true){
    //do stuff
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

When I look at the CPU usage it is almost 100% ... is there any way to do something like this while preserving CPU cycles without having to use complicated condition variables?

EDIT: "do stuff" checks a queue to see if there are any events to send... if there are none, then it does nothing (super fast), otherwise it sends the events via HTTP. It is very rare to have an event (e.g once every 10 minutes).

I know you could re-write this to use a condition variable but I'd prefer to figure out why there is so much CPU usage.

user491880
  • 4,709
  • 4
  • 28
  • 49
  • 1
    What is the 'do stuff' exactly? Any chance the CPU is busy doing this 'stuff', i.e. it runs much longer than 100ms? – valdo Jan 04 '22 at 15:59
  • It is pretty fast. Even if I set the sleep time to 1 or 2 seconds I still get 99% CPU usage. – user491880 Jan 04 '22 at 16:04
  • 1
    A condition variable isn't that complicated. The question implies the code is multithreaded, which implies the synchronization concerns are already addressed which is the most complicated part of using a condition variable. – François Andrieux Jan 04 '22 at 16:05
  • There isn't enough information here to identify the reason for the high CPU usage. The cause is likely hidden in the details of `//do stuff`. – François Andrieux Jan 04 '22 at 16:07
  • Did you use a profiler to see what's actually executing when the CPU usage is that high? Any chance it's in another thread entirely? – Stephen Newell Jan 04 '22 at 16:09

2 Answers2

1

I figured out the reason: During the logic of the code ("// do stuff") there was a continue statement. The continue statement caused the thread to skip over the sleep statement causing it to loop continuously. I moved the thread_sleep to the top of the while loop and the CPU usage went from 99% to 0.1%

user491880
  • 4,709
  • 4
  • 28
  • 49
0

Thus loop is not what’s consuming the CPU. Use a profiler to see what thread is actually busy. And with 100% CPU use, it implies that all cores are busy. On multi core CPUs, one busy thread never consumes 100% CPU by itself.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313