C语言 Windows 中的睡眠功能,使用 C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3379139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:03:24  来源:igfitidea点击:

Sleep function in Windows, using C

cwindowssleep

提问by RYN

I need to sleep my program in Windows. What header file has the sleep function?

我需要在 Windows 中休眠我的程序。什么头文件有睡眠功能?

回答by

Use:

用:

#include <windows.h>

Sleep(sometime_in_millisecs); // Note uppercase S

And here's a small example that compiles with MinGWand does what it says on the tin:

这是一个使用MinGW编译的小例子,并按照它在罐头上所说的做:

#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep(3000); // Sleep three seconds
    printf("sleep ended\n");
}

回答by Oleg

SleepExfunction (see http://msdn.microsoft.com/en-us/library/ms686307.aspx) is the best choise if your program directly or indirectly creates windows (for example use some COM objects). In the simples cases you can also use Sleep.

SleepEx如果您的程序直接或间接创建窗口(例如使用某些 COM 对象),则函数(请参阅http://msdn.microsoft.com/en-us/library/ms686307.aspx)是最佳选择。在简单的情况下,您也可以使用Sleep.

回答by abelenky

MSDN: Header: Winbase.h (include Windows.h)

MSDN:标题:Winbase.h(包括 Windows.h)

回答by user2876907

Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.

每当您想忙等待时,请在代码的开头包含以下函数。这与睡眠不同,因为在此函数运行时,进程将使用 100% 的 CPU。

void sleep(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock())
        ;
}

Note that the name sleepfor this function is misleading, since the CPU will not be sleeping at all.

请注意,sleep此函数的名称具有误导性,因为 CPU 根本不会休眠。