Reputation: 3208
How would I make a version of sleep in C spin so it uses cpu cycles?
Upvotes: 0
Views: 375
Reputation: 134841
What you want to do is a busy wait where you loop until a certain amount of time has elapsed. Just get the current time (using the highest precision timer available) and loop until the current time is a certain amount of time after you started.
Here's a concrete example using the Windows API and the performance counter using the two associated functions, QueryPerformanceCounter()
and QueryPerformanceFrequency()
.
void Sleep_spin(DWORD dwMilliseconds)
{
LARGE_INTEGER freq, target, current;
/* get the counts per second */
if (!QueryPerformanceFrequency(&freq)) { /* handle error */ }
/* set target to dwMilliseconds worth of counts */
target.QuadPart = freq.QuadPart * dwMilliseconds / 1000;
/* get the current count */
if (!QueryPerformanceCounter(¤t)) { /* handle error */ }
/* adjust target to get the ending count */
target.QuadPart += current.QuadPart;
/* loop until the count exceeds the target */
do
{
if (!QueryPerformanceCounter(¤t)) { /* handle error */ }
} while (current.QuadPart < target.QuadPart);
}
Use the appropriate API in your case, whatever that may be.
Upvotes: 2
Reputation: 81684
I suppose something like (pseudocode)
while (time < endtime)
;
The implementation of "time < endtime" is OS-dependent, but you just want to compute the end time based on an argument before your loop starts, and then continuously fetch the system time and compare it to that end time.
Upvotes: 4