Dormir durante milisegundos


Sé que la función POSIX sleep(x) hace que el programa duerma durante x segundos. ¿Hay una función para hacer que el programa duerma durante x milisegundos en C++?

Author: Prasanth Madhavan, 2010-11-15

14 answers

Tenga en cuenta que no hay una API C estándar para milisegundos, por lo que (en Unix) tendrá que conformarse con usleep, que acepta microsegundos:

#include <unistd.h>

unsigned int microseconds;
...
usleep(microseconds);
 364
Author: Niet the Dark Absol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-02 20:23:02

En C++11, puede hacer esto con las instalaciones de la biblioteca estándar:

#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));

Claro y legible, ya no es necesario adivinar qué unidades toma la función sleep().

 905
Author: HighCommander4,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-14 09:16:01

Para mantenerte portátil puedes usar Boost:: Thread para dormir:

#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;
}

Esta respuesta es un duplicado y se ha publicado en esta pregunta antes. Tal vez usted podría encontrar algunas respuestas utilizables allí también.

 77
Author: MOnsDaR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:36

Dependiendo de su plataforma, puede tener usleep o nanosleep disponible. usleep está obsoleto y se ha eliminado del estándar POSIX más reciente; se prefiere nanosleep.

 31
Author: CB Bailey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-15 12:54:37

En Unix se puede usar usleep.

En Windows hay Sleep.

 29
Author: INS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-19 20:41:45

¿Por qué no usar el tiempo?h biblioteca? Se ejecuta en sistemas Windows y POSIX:

#include <iostream>
#include <time.h>

using namespace std;

void sleepcp(int milliseconds);

void sleepcp(int milliseconds) // Cross-platform sleep function
{
    clock_t time_end;
    time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000;
    while (clock() < time_end)
    {
    }
}
int main()
{
    cout << "Hi! At the count to 3, I'll die! :)" << endl;
    sleepcp(3000);
    cout << "urrrrggghhhh!" << endl;
}

Código corregido - ahora la CPU permanece en estado INACTIVO [2014.05.24]:

#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;
}
 18
Author: Bart Grzybicki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-06 17:44:19

nanosleep es una mejor opción que usleep - es más resistente contra interrupciones.

 17
Author: Johan Kotlinski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-15 12:54:15
#include <WinBase.h>

Sintaxis:

Sleep (  __in DWORD dwMilliseconds   );

Uso:

Sleep (1000); //Sleeps for 1000 ms or 1 sec
 9
Author: foobar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 10:07:52

Si utiliza MS Visual C++ 10.0, puede hacer esto con las instalaciones de la biblioteca estándar:

Concurrency::wait(milliseconds);

Necesitarás:

#include <concrt.h>
 6
Author: Metronit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-08 12:24:47

La forma de dormir su programa en C++ es el método Sleep(int). El archivo de cabecera es #include "windows.h."

Por ejemplo:

#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;
}

El tiempo que duerme se mide en milisegundos y no tiene límite.

Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds
 4
Author: genius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-06 17:47:57

La llamada Select es una forma de tener más precisión (el tiempo de espera se puede especificar en nanosegundos).

 3
Author: Madhava Gaikwad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-15 13:17:16

En plataformas con la función select (POSIX, Linux y Windows) puedes hacer:

void sleep(unsigned long msec) {
    timeval delay = {msec / 1000, msec % 1000 * 1000};
    int rc = ::select(0, NULL, NULL, NULL, &delay);
    if(-1 == rc) {
        // Handle signals by continuing to sleep or return immediately.
    }
}

Sin embargo, hay mejores alternativas disponibles hoy en día.

 3
Author: Maxim Egorushkin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-06 17:49:29

Use hilos de entrada/salida asíncronos Boost, suspensión durante x milisegundos;

#include <boost/thread.hpp>
#include <boost/asio.hpp>

boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
 3
Author: Anum Sheraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-06 17:50:26

Como reemplazo de Win32 para sistemas POSIX:

void Sleep(unsigned int milliseconds) {
    usleep(milliseconds * 1000);
}

while (1) {
    printf(".");
    Sleep((unsigned int)(1000.0f/20.0f)); // 20 fps
}
 0
Author: lama12345,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-17 16:02:33