I need a better solution to a while loop that continualy checks the current time against the time that the user would like the program to end. This loop spikes the processor usage to 100%.

while( time(NULL) <= endTime )
  {
      printf("\r%4d", endTime - time(NULL));
  }

Thanks in advance.

Recommended Answers

All 3 Replies

Try _sleep(1); , you could also add this to a low priority thread that the app waits for to die.

edit:
Also printf() will interrupt the whole process, so only use it on so many increments of time.

Thanks for the help MosaicFuneral.
Is sleep portable, I have read that it is limited to Windows?
I don't have another environment to test in near by.

no it's not portable. there is no truly portable solution. you'll have to #define the sleep routine according to the detected OS at build time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.