CPU usage

Hello. I wrote code below on Ubuntu and it seems to eat whole 99 - 100 % of CPU usage (according to htop). Any suggestions on minimizing usage?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <ctime>
#include <cstdlib>

int main()
{
	int s = 0;
	for(time_t start = time(NULL); ; ) // Even empty loop "eats" 100 %
	{
		if(time(NULL) == start + s)
		{
			// DoStuff(); 
			s++;
		}
	}
	return 0;
}
Last edited on
There is no such thing as a truly empty loop - all loops must do two things:
- check their loop condition
- restart the loop at the next iteration
Since your program only does those two things over and over, never pausing to do something else, it gets full attention from your processor.

If you want your program to wait idle for a certain period of time, use a sleep function. There is Sleep on Windows, sleep on *nix, and there are also standard portable functions for it in C++11:
http://en.cppreference.com/w/cpp/thread/sleep_for
http://en.cppreference.com/w/cpp/thread/sleep_until
Topic archived. No new replies allowed.