【发布时间】:2011-07-23 08:38:05
【问题描述】:
如何在 C spin 中创建一个 sleep 版本,以便它使用 cpu 周期?
【问题讨论】:
-
所以你的问题是如何编写旋转的睡眠函数?
-
是的,我如何使自定义睡眠功能旋转
标签: c multithreading locking x86 sleep
如何在 C spin 中创建一个 sleep 版本,以便它使用 cpu 周期?
【问题讨论】:
标签: c multithreading locking x86 sleep
您想要做的是 busy wait 循环,直到经过一定时间。只需获取当前时间(使用可用的最高精度计时器)并循环直到当前时间是您开始后的一定时间。
这是一个使用 Windows API 和使用两个关联函数 QueryPerformanceCounter() 和 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);
}
根据您的情况使用适当的 API,无论是什么。
【讨论】:
我想像(伪代码)
while (time < endtime)
;
“time
【讨论】:
你还需要什么吗?
for (; ; ) ;
?
【讨论】: