睡眠數毫秒

我知道POSIX sleep(x)函數使程序休眠x秒。 在C ++中是否有使程序休眠x 毫秒的功能? ios


#1樓

在C ++ 11中,可使用標準庫工具來執行此操做: windows

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

清晰易讀,無需再猜想sleep()函數採用的單位。 函數


#2樓

#include <windows.h>

句法: 工具

Sleep (  __in DWORD dwMilliseconds   );

用法: this

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

#3樓

爲何不使用time.h庫? 在Windows和POSIX系統上運行: spa

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

更正的代碼-如今,CPU保持空閒狀態[2014.05.24]: code

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

#4樓

使用C ++ Sleep(int)程序的方法是Sleep(int)方法。 它的頭文件是#include "windows.h." orm

例如: it

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

它的睡眠時間以毫秒爲單位,沒有限制。 io

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

#5樓

若是使用MS Visual C ++ 10.0,則可使用標準庫工具執行此操做:

Concurrency::wait(milliseconds);

你會須要:

#include <concrt.h>
相關文章
相關標籤/搜索