Question

How to Sleep for Milliseconds in C++

cpplinuxsleep

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() or nanosleep()
  • 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.

Take Quiz

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> provides std::this_thread::sleep_for
  • <chrono> provides time units such as milliseconds
  • sleep_for pauses the current thread for at least the given duration

Another example

#include <thread>
#include <chrono>

int main() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::this_thread::sleep_for(std::chrono::milliseconds(250));
}

This waits:

  • 1 second
  • then 250 milliseconds

Older POSIX example

#include <unistd.h>

int main() {
    usleep(500000); // 500,000 microseconds = 500 milliseconds
}

This works on many POSIX systems, but usleep() is older and not the preferred modern C++ solution.

POSIX nanosleep() example

#include <time.h>

int main() {
    timespec ts;
    ts.tv_sec = 0;
    ts.tv_nsec = 500000000; // 500 milliseconds
    nanosleep(&ts, nullptr);
}

This is more flexible than sleep(), but still lower-level than modern C++ chrono-based code.

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

  1. The program prints Start.
  2. It reaches sleep_for(std::chrono::milliseconds(1000)).
  3. std::chrono::milliseconds(1000) creates a duration object representing 1000 milliseconds.
  4. sleep_for(...) tells the current thread to pause for at least that duration.
  5. After about 1 second, the thread resumes.
  6. 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 < 5; ++i) {
        std::cout << "Checking...\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}
Take Quiz

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

4. Configuration-driven delays

int delayMs = 250;
std::this_thread::sleep_for(std::chrono::milliseconds(delayMs));

This is common when delay values come from config files or command-line arguments.

Important practice

In many real systems, sleep is only a simple tool. For more robust designs, developers often prefer:

  • condition variables
  • timers
  • event loops
  • async callbacks

These are often better than repeatedly sleeping and checking.

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); // only 500 microseconds, not 500 milliseconds

500 milliseconds would be:

usleep(500000);

This is one reason chrono-based durations are easier to read.

4. Expecting exact timing

Sleep usually guarantees a minimum wait, not perfect precision.

Avoid assumptions like:

  • “this will always resume exactly after 10.000 ms”

Real systems depend on OS scheduling and timer resolution.

5. Using sleep instead of proper synchronization

Sometimes beginners write:

std::this_thread::sleep_for(std::chrono::milliseconds(100));
// assume another thread has finished by now

This is unreliable. Prefer proper synchronization tools such as:

  • std::mutex
  • std::condition_variable
  • std::future
  • join()

6. Forgetting compiler support for C++11 or newer

std::this_thread::sleep_for requires modern C++ support.

For example, with g++ you may need:

g++ -std=c++11 main.cpp -o app

Comparisons

OptionLanguage/PlatformUnit StylePortable C++Notes
sleep(x)POSIXSecondsNoSimple, but only second-level granularity
usleep(x)POSIXMicrosecondsNoOlder API, less preferred today
nanosleep()POSIXSeconds + nanosecondsNoFlexible but lower-level
Sleep(x)WindowsMillisecondsNoWindows-specific API
std::this_thread::sleep_for(...)Standard C++11+chrono durationsYesPreferred modern solution

sleep_for vs sleep_until

FunctionUse case
sleep_for(duration)Sleep for a relative amount of time, such as 500 ms
sleep_until(time_point)Sleep until a specific clock time point

If you simply want “wait 200 milliseconds,” use sleep_for.

Take Quiz

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 seconds
  • usleep() uses microseconds
  • Sleep() on Windows uses milliseconds
  • std::this_thread::sleep_for is the standard C++ choice
  • Sleep duration is usually minimum time, not exact wake-up time
  • Use <thread> and <chrono>

Best practice

Prefer:

std::this_thread::sleep_for(std::chrono::milliseconds(ms));

instead of manual unit conversion.

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.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more