x86 gcc 睡眠块还是旋转?

发布于 2024-10-26 22:35:36 字数 42 浏览 1 评论 0原文

我如何在 C spin 中制作一个睡眠版本,以便它使用 cpu 周期?

How would I make a version of sleep in C spin so it uses cpu cycles?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

还在原地等你 2024-11-02 22:35:36

我想像(伪代码)

while (time < endtime)
    ; 

“time < endtime”的实现是依赖于操作系统的,但你只想在循环开始之前根据参数计算结束时间,然后连续获取系统时间并将其与那个结束时间。

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.

迷鸟归林 2024-11-02 22:35:36

您想要做的是忙碌等待,循环直到经过一定时间。只需获取当前时间(使用可用的最高精度计时器)并循环,直到当前时间达到启动后的一定时间。

下面是使用 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。

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.

┊风居住的梦幻卍 2024-11-02 22:35:36

除了这些之外,你还需要什么吗

for (; ; ) ;

Did you need anything more than just

for (; ; ) ;

?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文