【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
我知道POSIX sleep(x)
函数使程序休眠x秒。 在C ++中是否有使程序休眠x 毫秒的功能?
#1楼
在C ++ 11中,可以使用标准库工具来执行此操作:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));
清晰易读,无需再猜测sleep()
函数采用的单位。
#2楼
#include <windows.h>
句法:
Sleep ( __in DWORD dwMilliseconds );
用法:
Sleep (1000); //Sleeps for 1000 ms or 1 sec
#3楼
为什么不使用time.h库? 在Windows和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;
}
更正的代码-现在,CPU保持空闲状态[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;
}
#4楼
使用C ++ Sleep(int)
程序的方法是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
#5楼
如果使用MS Visual C ++ 10.0,则可以使用标准库工具执行此操作:
Concurrency::wait(milliseconds);
你会需要:
#include <concrt.h>
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3153726