C++ example

How to sleep for milliseconds in C++

7 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Include <thread> and <chrono> and call std::this_thread::sleep_for(std::chrono::milliseconds(100)). With using namespace std::chrono_literals; the same call is std::this_thread::sleep_for(100ms). It pauses only the calling thread, for at least that long. It is standard since C++11, so it replaces usleep (POSIX) and Sleep (Windows).

C++ has no sleep(ms) taking a bare number: the standard sleep functions take a std::chrono duration, so the unit is part of the type and 100 can never mean seconds by mistake. The sections below cover sleep_for with milliseconds, other units and fractions, sleep_until for loops that must keep a steady rate, what a sleep does to other threads, and a sleep another thread can cancel, then a table to pick from. The sleeps are kept short so the page stays quick. Each example runs on this page: hit Run, then edit the code and run it again.

1std::this_thread::sleep_forRecommended

std::this_thread::sleep_for blocks the current thread for a duration. Spell the unit out with std::chrono::milliseconds(100), or bring in the chrono literals and write 100ms. When the delay is an int (from a config file, say), wrap it in the unit it is measured in. To check how long a sleep really took, read std::chrono::steady_clock before and after: it only moves forward, unlike system_clock, which jumps when the system time is set.

sleep_for.cpp
#include <chrono>
#include <iostream>
#include <thread>

int main() {
    using namespace std::chrono_literals;  // enables 100ms, 2s, 500us

    std::cout << "start\n";
    // The long form names the unit
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::cout << "after 100 ms\n";

    // The same pause with a chrono literal
    std::this_thread::sleep_for(100ms);
    std::cout << "after another 100 ms\n";

    // A delay held in an int: wrap it in the unit it is measured in
    int delay_ms = 50;
    std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
    std::cout << "after " << delay_ms << " ms more\n";

    // Measure with steady_clock: it never jumps when the system time changes
    auto start = std::chrono::steady_clock::now();
    std::this_thread::sleep_for(150ms);
    auto elapsed = std::chrono::steady_clock::now() - start;
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
    std::cout << std::boolalpha;
    std::cout << "slept at least 150 ms: " << (ms >= 150ms) << '\n';
}

Output

Each line appears after its pause, and the measured sleep prints slept at least 150 ms: true. The program prints that comparison instead of the raw time because the exact figure changes from run to run: a sleep is a minimum. The thread becomes ready to run once the time is up, and the scheduler decides when it actually does, so expect a little more, often a fraction of a millisecond on Linux and up to one timer tick (about 15.6 ms by default) on Windows. Never use a sleep to wait for another thread to finish something; join it or use a condition variable (section 5).

2Seconds, microseconds and fractions

sleep_for takes any std::chrono::duration: 2500us, std::chrono::seconds(2), std::chrono::minutes(1). For a fraction, use a duration with a double count: std::chrono::duration<double> counts seconds and std::chrono::duration<double, std::milli> counts milliseconds. Durations of different units add and compare correctly, which is the point of putting the unit in the type.

durations.cpp
#include <chrono>
#include <iostream>
#include <ratio>
#include <thread>

int main() {
    using namespace std::chrono_literals;
    using std::chrono::steady_clock;
    std::cout << std::boolalpha;

    // Any duration type works: microseconds, seconds, minutes...
    std::this_thread::sleep_for(2500us);  // 2.5 ms

    // Fractions: duration<double> counts seconds,
    // duration<double, std::milli> counts milliseconds
    auto start = steady_clock::now();
    std::this_thread::sleep_for(std::chrono::duration<double>(0.05));
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(12.5));
    auto slept = steady_clock::now() - start;
    std::cout << "0.05 s + 12.5 ms slept: " << (slept >= 62ms) << '\n';

    // Zero and negative durations return at once
    start = steady_clock::now();
    std::this_thread::sleep_for(0ms);
    std::this_thread::sleep_for(-5ms);
    auto waited = steady_clock::now() - start;
    std::cout << "0ms and -5ms returned at once: " << (waited < 5ms) << '\n';

    // Durations mix freely; the result has the finer unit (C++20 prints units)
    auto total = 1s + 250ms;
    std::cout << "1s + 250ms = " << total << '\n';
    std::cout << "as a number: " << total.count() << '\n';
    std::chrono::duration<double> secs = total;  // to double never loses data
    std::cout << "in seconds: " << secs.count() << '\n';

    // milliseconds holds a whole number: a double needs duration_cast,
    // which truncates toward zero
    double delay = 12.7;
    auto whole = std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::duration<double, std::milli>(delay));
    std::cout << "12.7 as milliseconds: " << whole << '\n';
}

Output

The fractional sleeps print 0.05 s + 12.5 ms slept: true, and a zero or negative duration returns at once (0ms and -5ms returned at once: true), so a computed delay that went negative is harmless. Adding 1s + 250ms gives 1250ms: the sum takes the finer unit, and C++20 can print a duration with its unit. .count() gives the bare number, 1250. Converting to a coarser or integer unit can lose data, so it needs duration_cast, which truncates: 12.7 becomes 12ms. Writing std::chrono::milliseconds d(x) with a double x does not compile at all.

3A steady rate with sleep_until

A loop that does some work and then sleeps for its period runs slower than that period: each round takes the work time plus the sleep, and the error adds up. To run something every 50 ms, keep a time point for the next round, add the period to it, and call std::this_thread::sleep_until(next). The sleep then shrinks by however long the work took. Use steady_clock time points: a deadline on system_clock moves when someone changes the system time.

sleep_until.cpp
#include <chrono>
#include <iostream>
#include <thread>

using namespace std::chrono_literals;

// Stands in for real work that takes about 20 ms
void work() {
    std::this_thread::sleep_for(20ms);
}

int main() {
    using clock = std::chrono::steady_clock;
    constexpr auto period = 50ms;
    constexpr int ticks = 4;
    std::cout << std::boolalpha;

    // sleep_for after the work: every tick takes work + period, so it drifts
    auto start = clock::now();
    for (int i = 0; i < ticks; ++i) {
        work();
        std::this_thread::sleep_for(period);
    }
    auto drifting = clock::now() - start;
    std::cout << "sleep_for loop took >= 280 ms: " << (drifting >= 280ms) << '\n';

    // sleep_until a schedule: the wait shrinks by however long the work took
    start = clock::now();
    auto next = start;
    for (int i = 0; i < ticks; ++i) {
        work();
        next += period;
        std::this_thread::sleep_until(next);
    }
    auto fixed = clock::now() - start;
    std::cout << "sleep_until loop took >= 200 ms: " << (fixed >= 200ms) << '\n';
    std::cout << "sleep_until loop was shorter: " << (fixed < drifting) << '\n';

    // A time point in the past returns at once
    auto t0 = clock::now();
    std::this_thread::sleep_until(t0 - 1s);
    auto waited = clock::now() - t0;
    std::cout << "past deadline returned at once: " << (waited < 50ms) << '\n';
}

Output

Four rounds of 20 ms work and a 50 ms period take at least 280 ms with sleep_for (sleep_for loop took >= 280 ms: true), and finish sooner with sleep_until (sleep_until loop was shorter: true), because the schedule, not the work, sets the pace. A deadline already in the past returns at once (past deadline returned at once: true). That is also the catch: if one round overruns its period, the next deadlines are already behind, and the loop runs several rounds back to back to catch up. When skipping is better, check if (next < clock::now()) and reset next to clock::now().

4Only the calling thread sleeps

std::this_thread::sleep_for pauses the thread that calls it and nothing else. Other threads keep running, and several threads sleeping at once wait in parallel, so three sleeps of 200 ms on three threads take about 200 ms in total. That makes a sleeping worker thread the simple way to do something later without stopping the rest of the program.

threads.cpp
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>

int main() {
    using namespace std::chrono_literals;
    using clock = std::chrono::steady_clock;
    std::cout << std::boolalpha;

    // Three threads sleep 200 ms each, at the same time
    auto start = clock::now();
    std::vector<std::thread> workers;
    for (int i = 0; i < 3; ++i) {
        workers.emplace_back([] { std::this_thread::sleep_for(200ms); });
    }

    // main is not paused by their sleeps: it runs on right away
    auto main_free = clock::now() - start;
    std::cout << "main went on while they slept: " << (main_free < 100ms) << '\n';

    for (auto& w : workers) {
        w.join();
    }
    auto total = clock::now() - start;
    // 3 x 200 ms in parallel takes about 200 ms, not 600 ms
    std::cout << "all done in >= 200 ms: " << (total >= 200ms) << '\n';
    std::cout << "all done in < 600 ms: " << (total < 600ms) << '\n';
}

Output

main carries on while the workers sleep (main went on while they slept: true), and the three sleeps end together: all done in >= 200 ms: true and all done in < 600 ms: true, less than the 600 ms three sleeps in a row would take. A sleeping thread uses no CPU, unlike a loop that keeps reading the clock until the time is up, which burns a whole core to do the same thing. In the single thread of a GUI or game loop, though, a sleep freezes everything that thread draws or handles for that long.

5A sleep another thread can cut short

A thread inside sleep_for(5s) cannot be woken: shutting down means waiting out the rest of the five seconds. When a wait must end early on request, wait on a std::condition_variable instead. wait_for(lock, 5s, pred) sleeps up to five seconds but returns as soon as another thread makes pred true and calls notify_one. C++20 packages the same idea: std::jthread passes its function a std::stop_token, and std::condition_variable_any::wait_for with that token wakes when request_stop() is called.

cancel_sleep.cpp
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <stop_token>
#include <thread>

using namespace std::chrono_literals;
using clock_type = std::chrono::steady_clock;

int main() {
    std::cout << std::boolalpha;

    // C++11: wait_for on a condition variable sleeps up to 5 s,
    // but returns as soon as another thread sets the flag and notifies
    std::mutex m;
    std::condition_variable cv;
    bool stop = false;
    bool stopped_early = false;
    std::thread worker([&] {
        std::unique_lock lock(m);
        // true: the flag was set; false: the full 5 s ran out
        stopped_early = cv.wait_for(lock, 5s, [&] { return stop; });
    });
    std::this_thread::sleep_for(50ms);
    auto t0 = clock_type::now();
    {
        std::lock_guard lock(m);
        stop = true;
    }
    cv.notify_one();
    worker.join();
    std::cout << "cv: stopped early: " << stopped_early << '\n';
    auto waited = clock_type::now() - t0;
    std::cout << "cv: joined in < 1 s: " << (waited < 1s) << '\n';

    // C++20: std::jthread hands the thread a stop_token, and
    // condition_variable_any::wait_for with that token wakes on request_stop()
    std::jthread ticker([](std::stop_token token) {
        std::mutex tm;
        std::condition_variable_any tcv;
        std::unique_lock lock(tm);
        tcv.wait_for(lock, token, 5s, [] { return false; });
    });
    std::this_thread::sleep_for(50ms);
    t0 = clock_type::now();
    ticker.request_stop();
    ticker.join();  // the jthread destructor would also stop and join
    waited = clock_type::now() - t0;
    std::cout << "jthread: joined in < 1 s: " << (waited < 1s) << '\n';
}

Output

Both waits were set for 5 s and both threads were joined within a second (cv: joined in < 1 s: true, jthread: joined in < 1 s: true). wait_for returns the predicate's value, so cv: stopped early: true tells a stop request apart from a timeout. Always pass a predicate: a condition variable can wake without a notify (a spurious wakeup), and the predicate also covers a notify sent before the thread started waiting. Set the flag under the mutex, or the notify can slip in between the check and the wait. A std::jthread also requests a stop and joins in its destructor, so leaving its scope ends the wait.

6Which should you use?

MethodCan be cut shortStandardBest for
std::this_thread::sleep_for(100ms)NoC++11A plain pause or delay
std::this_thread::sleep_until(next)NoC++11Loops at a fixed rate, deadlines
condition_variable::wait_for(lock, d, pred)Yes, by notifyC++11Waits another thread may end early
condition_variable_any::wait_for(lock, token, d, pred)Yes, by request_stopC++20std::jthread workers
usleep / nanosleep / SleepNoPOSIX / WindowsAvoid: not portable
Loop until the clock passes a timen/aAnyAvoid: keeps a CPU core busy

Frequently asked questions

Why does std::this_thread::sleep_for(100) not compile?

sleep_for takes a std::chrono::duration, and a plain int does not convert to one, because nothing says whether 100 means milliseconds or seconds. GCC reports no matching function for call to 'sleep_for(int)'. Write the unit: std::this_thread::sleep_for(std::chrono::milliseconds(100)), or 100ms after using namespace std::chrono_literals;.

How do I sleep for seconds or half a second in C++?

Use a duration of that unit: std::this_thread::sleep_for(std::chrono::seconds(2)) or 2s with the chrono literals. For a fraction, 500ms is the clearest, and std::chrono::duration<double>(0.5) takes a double number of seconds. The literal 0.5s also works: a floating-point chrono literal makes a duration with a long double count.

Should I use usleep or Sleep in C++?

Not in new code. usleep (microseconds) and sleep (whole seconds) come from the POSIX header <unistd.h>, and usleep was removed from POSIX in 2008 in favour of nanosleep. Sleep (capital S, milliseconds) comes from <windows.h> and exists only on Windows. std::this_thread::sleep_for works on both, takes any unit, and on Linux calls nanosleep underneath.

How accurate is std::this_thread::sleep_for?

It sleeps at least the requested time, never less, and usually a little more: the thread is woken when the time is up and then waits for the scheduler. On Linux the extra is often well under a millisecond; on Windows the default timer tick is about 15.6 ms, so a 1 ms sleep can take that long. For a steady rate, use sleep_until with a schedule so the errors do not add up, and measure with std::chrono::steady_clock.

Does sleep_for block the whole program?

No, only the thread that calls it. Other threads keep running, and in a single-threaded program that is the whole program. To delay one task without stopping the rest, run it on its own std::thread or std::jthread that sleeps first. A sleeping thread uses no CPU.

How do I stop a thread that is sleeping?

You cannot wake a thread out of sleep_for; it returns only when its time is up. Make it wait on a condition variable instead: cv.wait_for(lock, 5s, [&] { return stop; }) returns early when another thread sets stop under the mutex and calls cv.notify_one(). In C++20, give a std::jthread a std::stop_token and wait with std::condition_variable_any::wait_for(lock, token, 5s, pred), which returns when request_stop() is called.

Run it yourself

Open any of these in the full C++ editor to tweak, run and share.

C++ playground