I'm trying to write a program which will always loop.
Besides that, i also use a function called wait() within the loop.
The wait() function is to make sure the loop runs once each second.
But one problem arise:
The program used up all my CPU usage until 98% all the time!

My program is look like this:
while(condition == true)
{
//codes
wait();
}

It's there any programming method which will save more CPU usage while using a loop?

Dani AI

Generated

Brief summary and practical follow-ups to the answers from and .

A tight loop that "waits" by busy-waiting will consume CPU. The right approach is to block the thread or let the OS scheduler put it to sleep instead of polling. On modern C++ prefer the standard threading/timing tools (for example, use a timed sleep or a condition variable with a timed wait) so the thread does not spin and the CPU is freed for other work. For periodic tasks, compute the next target time with a monotonic clock (steady_clock) and sleep until that instant to avoid cumulative drift.

On Windows, platform APIs offer better options than busy polling: use waitable timers or synchronization waits to get millisecond or better behavior without burning CPU. If mixing platform headers and legacy console headers, collisions can occur because Windows pulls in a lot of symbols; a common practical fix is to minimize what Windows.h imports (define WIN32_LEAN_AND_MEAN and NOMINMAX before including it) or prefer the C++ standard headers where possible. If an include-order change fixed the redefinition error for , that is an acceptable short-term workaround; for long-term code, prefer standard threading/timing APIs or isolate platform-specific code behind small adapters.

Troubleshooting notes: confirm your loop truly blocks (use a profiler or Task Manager), check thread priority, and watch for other busy threads. If precise periodic timing is required, use a high-resolution timer and correct for sleep jitter by recalculating the next wake time rather than sleeping a fixed interval repeatedly.

Recommended Answers

All 2 Replies

change the wait function to use less cpu by using the Sleep, SleepEx or usleep(linux) commands. Note that the precision of these functions might sometimes be worse than 10ms, so if you need accurate timing, you might wish to use a good timebase in conjuction with these functions.

It's works!
But when i run the source code, i found that windows.h must be included before conio.h. If not it will be a redefine function error.
Why?

Anyway, thanks again dougy83!
U saved my day!

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.