C++ scheduling

I've run a few programs with main loops that will go forever until the user exits, but these have always run asynchronously and take up 100% of a CPU. I'm writing a console app and would like to implement a scheduler that uses standard libraries in Windows.

This seems to work upon initial testing, but is this a reliable way to do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define WIN32_LEAN_AND_MEAN // Omits rarely used windows stuff

#include <Windows.h> // Uses Sleep() command
#include <ctime> // time_t, time() and difftime()
#include <iostream>

int main()
{
	double dT_demanded = 1./60.; // 60 Hz iteration rate
	time_t now, then;

	//Initializing function calls here

	while (true)
	{
		time(&then);

		//Iterating function calls here

		time(&now);
		double dT_actual = difftime(now, then);

		if (dT_actual > dT_demanded) std::cout << "Warning, iteration overflow" << std::endl;
		else                         Sleep((DWORD)((dT_demanded - dT_actual)*1000));
	}
	return 0;
}
Last edited on
Topic archived. No new replies allowed.