Question
I know that the POSIX sleep(x) function pauses a program for x seconds. Is there a way in C++ to pause execution for x milliseconds instead?
Short Answer
By the end of this page, you will understand how to pause a C++ program for milliseconds, which APIs are commonly used, and why modern C++ usually prefers std::this_thread::sleep_for over older platform-specific functions.
Concept
Pausing a program for a short amount of time is called sleeping or delaying execution. This is useful when you want a thread to wait before continuing.
In older POSIX code, sleep() only works in seconds. If you need smaller units such as milliseconds or microseconds, you need a different function.
In modern C++, the standard and portable way is:
std::this_thread::sleep_for(...);
This function was introduced in C++11 and works with the <chrono> library, which lets you express time safely using units like milliseconds, seconds, and nanoseconds.
Why this matters:
- It is portable across operating systems.
- It is clearer than older C APIs.
- It reduces mistakes caused by manually converting time units.
- It works naturally with modern multithreaded C++ code.
Older alternatives also exist:
- POSIX:
usleep()ornanosleep() - Windows:
Sleep()
But if you are writing standard C++, std::this_thread::sleep_for is usually the best choice.
Mental Model
Think of your program as a worker following instructions.
sleep(2)means: “take a 2-second break.”sleep_for(std::chrono::milliseconds(500))means: “take a 500-millisecond break.”
The important detail is that the worker is not stopping the whole computer—only that specific thread is pausing before continuing to the next instruction.
Syntax and Examples
Modern C++ syntax
#include <iostream>
#include <thread>
#include <chrono>
int main() {
std::cout << "Waiting...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "Done!\n";
}
How it works
<thread>providesstd::this_thread::sleep_for<chrono>provides time units such asmillisecondssleep_forpauses the current thread for at least the given duration
Another example
#include <thread>
#include <chrono>
int main {
std::this_thread::(std::chrono::());
std::this_thread::(std::chrono::());
}
Step by Step Execution
Consider this example:
#include <iostream>
#include <thread>
#include <chrono>
int main() {
std::cout << "Start\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "End\n";
}
Step by step
- The program prints
Start. - It reaches
sleep_for(std::chrono::milliseconds(1000)). std::chrono::milliseconds(1000)creates a duration object representing 1000 milliseconds.sleep_for(...)tells the current thread to pause for at least that duration.- After about 1 second, the thread resumes.
- The program prints
End.
Important note
The delay is usually at least the requested time, not guaranteed to be exact to the millisecond. The operating system scheduler may resume the thread slightly later.
Real World Use Cases
Sleeping for milliseconds is useful in many real programs:
- Retry logic: wait 200 ms before trying a failed network request again
- Polling: check whether a file, socket, or process is ready every 100 ms
- Rate limiting: slow down repeated actions to avoid overwhelming an API
- Animations or games: pause briefly between frames or updates
- Testing: simulate time passing in simple experiments or demos
- Background workers: sleep between periodic checks for new tasks
Example: simple retry delay
#include <thread>
#include <chrono>
void retryLater() {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
Example: periodic loop
#include <iostream>
#include <thread>
#include <chrono>
int main() {
for (int i = 0; i < ; ++i) {
std::cout << ;
std::this_thread::(std::chrono::());
}
}
Real Codebase Usage
In real projects, developers usually use sleep carefully rather than everywhere.
Common patterns
1. Retry with delay
for (int attempt = 1; attempt <= 3; ++attempt) {
if (connectToServer()) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
This adds a small wait between retries.
2. Polling loop
while (!jobFinished()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
This avoids a tight loop that wastes CPU.
3. Guarding against busy waiting
Without sleep:
while (!ready) {
// wastes CPU by spinning constantly
}
With sleep:
while (!ready) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
Common Mistakes
1. Using sleep() when you need milliseconds
Broken idea:
sleep(500);
This means 500 seconds, not 500 milliseconds.
Use instead:
std::this_thread::sleep_for(std::chrono::milliseconds(500));
2. Forgetting the correct headers
Broken code:
int main() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
This will fail without:
#include <thread>
#include <chrono>
3. Mixing up microseconds and milliseconds
Broken expectation:
usleep(500);
Comparisons
| Option | Language/Platform | Unit Style | Portable C++ | Notes |
|---|---|---|---|---|
sleep(x) | POSIX | Seconds | No | Simple, but only second-level granularity |
usleep(x) | POSIX | Microseconds | No | Older API, less preferred today |
nanosleep() | POSIX | Seconds + nanoseconds | No | Flexible but lower-level |
Sleep(x) | Windows | Milliseconds | No | Windows-specific API |
Cheat Sheet
Quick reference
Modern C++
#include <thread>
#include <chrono>
std::this_thread::sleep_for(std::chrono::milliseconds(500));
Common duration types
std::chrono::seconds(1)
std::chrono::milliseconds(500)
std::chrono::microseconds(200)
std::chrono::nanoseconds(1000)
POSIX alternatives
sleep(1); // 1 second
usleep(500000); // 500 milliseconds
Rules to remember
sleep()uses secondsusleep()uses microsecondsSleep()on Windows uses milliseconds
FAQ
Is there a millisecond sleep function in standard C++?
Yes. Use std::this_thread::sleep_for(std::chrono::milliseconds(x)).
Can I use sleep(500) for 500 milliseconds?
No. sleep(500) means 500 seconds on POSIX systems.
What header do I need for sleep_for?
You need:
#include <thread>
#include <chrono>
Is usleep() still okay to use?
It may work on POSIX systems, but modern C++ code usually prefers std::this_thread::sleep_for because it is standard and clearer.
Does sleep_for block the whole program?
No. It pauses the current thread, not necessarily every thread in the program.
Is millisecond sleep exact?
Not usually. The thread sleeps for at least that long, but actual wake-up time may be slightly later.
Should I use sleep to wait for another thread?
Usually no. Proper synchronization tools such as join() or condition variables are more reliable.
Mini Project
Description
Build a small console program that prints a countdown with short pauses between each line. This demonstrates how to sleep for milliseconds using modern C++ and helps you see how timed delays affect program flow.
Goal
Create a C++ program that prints several messages with a 500-millisecond pause between them.
Requirements
- Print a starting message to the console.
- Use modern C++ sleep functionality, not POSIX
sleep(). - Pause for 500 milliseconds between countdown steps.
- Print a final message after the countdown ends.
Keep learning
Related questions
Basic Rules and Idioms for Operator Overloading in C++
Learn the core rules, syntax, and common idioms for operator overloading in C++, including member vs non-member operators.
C++ Base Class Constructor Rules Explained
Learn how C++ base class constructors are called from derived classes, including order, syntax, defaults, and common mistakes.
C++ Casts Explained: C-Style Cast vs static_cast vs dynamic_cast
Learn the difference between C-style casts, static_cast, and dynamic_cast in C++ with clear examples, safety rules, and real usage tips.