I'm working on a program that needs a consistent ~1ms sleep. The sleep is used in order to generate a hardware pulse of length ~1 ms.
I am using the following code for the sleep
void usleep(__int64 usec)
{
HANDLE timer;
LARGE_INTEGER ft;
ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative value indicates relative time
timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
}
taken from here
When I use the above code (using Embarcaderos bcc32 compiler) on a Intel i7, passing 1000 (1ms) I get a sleep that I measure using Poco's timestamp function to about 1ms. The code itself is executed in a thread.
The code looks like this:
mDebugFile << std::setprecision (17) << mPulseEventTime.elapsed()/1000.0 << "\t" << 0 << "\n";
setHigh(false);
mDebugFile << std::setprecision (17) << mPulseEventTime.elapsed()/1000.0 << "\t" << 1 << "\n";
usleep(1000);
mDebugFile << std::setprecision (17) << mPulseEventTime.elapsed()/1000.0 << "\t" << 1 << "\n";
setLow(false);
mDebugFile << std::setprecision (17) << mPulseEventTime.elapsed()/1000.0 << "\t" << 0 << "\n";
where the mDebugFile is a fstream object and setLow/setHigh are calls to the hardware.
However, when the same code is executed on a Xeon CPU, the sleep is measured to about 10 ms. Assuming that Poco's timing function gives the proper time, 10 ms is quite large, when asking for 1ms.
Is there any other way to get a reliable sleep for ~ 1ms? Can the Windows OS be modified to give a more reliable sleep?
I don't have access to boost or above C++11 features.