2023-05-14 07:00:05

休眠毫秒

我知道POSIX休眠(x)函数使程序休眠x秒。C++中是否有一个函数可以让程序休眠x毫秒?


当前回答

从C++14开始,使用std及其数字文本:

#include <chrono>
#include <thread>

using namespace std::chrono_literals;

std::this_thread::sleep_for(123ms);

其他回答

根据您的平台,您可以使用usleep或nanosleep。usleep已被弃用,并已从最新的POSIX标准中删除;纳米睡眠是优选的。

#include <windows.h>

语法:

Sleep (  __in DWORD dwMilliseconds   );

用法:

Sleep (1000); //Sleeps for 1000 ms or 1 sec

为什么不使用time.h库?在Windows和POSIX系统上运行(不要在生产中使用此代码!):

CPU保持空闲状态:

#include <iostream>
#ifdef _WIN32
    #include <windows.h>
#else
    #include <unistd.h>
#endif // _WIN32

using namespace std;

void sleepcp(int milliseconds);

void sleepcp(int milliseconds) // Cross-platform sleep function
{
    #ifdef _WIN32
        Sleep(milliseconds);
    #else
        usleep(milliseconds * 1000);
    #endif // _WIN32
}
int main()
{
    cout << "Hi! At the count to 3, I'll die! :)" << endl;
    sleepcp(3000);
    cout << "urrrrggghhhh!" << endl;
}

一个答案的优雅解决方案,有点修改。。如果没有更好的功能可用,可以很容易地添加select()用法。只需生成使用select()等的函数。。

代码:


#include <iostream>

/*
 Prepare defines for millisecond sleep function that is cross-platform
*/
#ifdef _WIN32
#  include <Windows.h>
#  define sleep_function_name           Sleep
#  define sleep_time_multiplier_for_ms      1
#else
#  include <unistd.h>
#  define sleep_function_name           usleep
#  define sleep_time_multiplier_for_ms      1000
#endif

/* Cross platform millisecond sleep */
void cross_platform_sleep_ms(unsigned long int time_to_sleep_in_ms)
{
   sleep_function_name ( sleep_time_multiplier_for_ms * time_to_sleep_in_ms );
}

注意,没有毫秒的标准C API,因此(在Unix上)您必须接受usleep,它接受微秒:

#include <unistd.h>

unsigned int microseconds;
...
usleep(microseconds);