2023-05-14 07:00:05

休眠毫秒

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


当前回答

#include <chrono>
#include <thread>

std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second

记住导入两个标头。

其他回答

为了保持便携性,您可以使用Boost::Thread进行睡眠:

#include <boost/thread/thread.hpp>

int main()
{
    //waits 2 seconds
    boost::this_thread::sleep( boost::posix_time::seconds(1) );
    boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );

    return 0;
}

此答案是重复的,以前已在该问题中发布过。也许你也可以在那里找到一些有用的答案。

#include <chrono>
#include <thread>

std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second

记住导入两个标头。

这个问题由来已久,但我设法找到了一个在我的应用程序中实现这一点的简单方法。您可以创建如下所示的C/C++宏:

#ifndef MACROS_H
#define MACROS_H

#include <unistd.h>

#define msleep(X) usleep(X * 1000)

#endif // MACROS_H

一个答案的优雅解决方案,有点修改。。如果没有更好的功能可用,可以很容易地添加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++中休眠程序的方法是sleep(int)方法。它的头文件是#include“windows.h”

例如:

#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;

int main()
{
    int x = 6000;
    Sleep(x);
    cout << "6 seconds have passed" << endl;
    return 0;
}

它的睡眠时间以毫秒为单位,没有限制。

Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds