Cách đa nền tảng để ngủ chương trình trong x mili giây sử dụng clock() (C++98) hoặc std::this_thread::sleep_for (C++11).
Cách 1: C++98 dùng clock()
#include <iostream>
#include <ctime>
using namespace std;
void sleepMs(int ms) {
clock_t end = clock() + ms * CLOCKS_PER_SEC / 1000;
while (clock() < end); // busy wait
}
int main() {
cout << "Bat dau dem 3 giay...\n";
sleepMs(3000);
cout << "Ket thuc.\n";
return 0;
}
Cách 2: C++11 std::this_thread::sleep_for (Khuyên dùng)
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main() {
cout << "Ngu 2.5 giay...\n";
this_thread::sleep_for(chrono::milliseconds(2500));
cout << "Da tinh!\n";
return 0;
}
Đầu ra
Bat dau dem 3 giay... (3 giây sau) Ket thuc.
Lưu ý
Cách clock() tiêu tốn CPU (busy wait). Cách C++11 nhường CPU cho tiến trình khác, hiệu quả hơn.