Sleep for milliseconds

2019-01-01 05:57发布

I know the POSIX sleep(x) function makes the program sleep for x seconds. Is there a function to make the program sleep for x milliseconds in C++?

标签: c++ linux sleep
14条回答
有味是清欢
2楼-- · 2019-01-01 06:33

The way to sleep your program in C++ is the Sleep(int) method. The header file for it is #include "windows.h."

For example:

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

The time it sleeps is measured in milliseconds and has no limit.

Second = 1000 milliseconds
Minute = 60000 milliseconds
Hour = 3600000 milliseconds
查看更多
妖精总统
3楼-- · 2019-01-01 06:34

As a Win32 replacement for POSIX systems:

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

while (1) {
    printf(".");
    Sleep((unsigned int)(1000.0f/20.0f)); // 20 fps
}
查看更多
其实,你不懂
4楼-- · 2019-01-01 06:38

In Unix you can use usleep.

In Windows there is Sleep.

查看更多
素衣白纱
5楼-- · 2019-01-01 06:43

nanosleep is a better choice than usleep - it is more resilient against interrupts.

查看更多
姐姐魅力值爆表
6楼-- · 2019-01-01 06:43

If using MS Visual C++ 10.0, you can do this with standard library facilities:

Concurrency::wait(milliseconds);

you will need:

#include <concrt.h>
查看更多
情到深处是孤独
7楼-- · 2019-01-01 06:45

Why don't use time.h library? Runs on Windows and POSIX systems:

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

Corrected code - now CPU stays in IDLE state [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;
}
查看更多
登录 后发表回答