Date: 2025jun29
Language: C++
Q. C++: sleep for nanoseconds, microseconds, milliseconds, seconds
A. In C++ the idiomatic way is to use chrono. This doesn't work in C - I have another page for that.
#include <iostream>
#include <chrono>
#include <thread>
int main() {
{
const long n = 1e9;
printf("Sleeping %ld nanoseconds\n", n);
std::this_thread::sleep_for(std::chrono::nanoseconds(n));
}
{
const useconds_t n = 1e6;
printf("Sleeping %ld microseconds\n", n);
std::this_thread::sleep_for(std::chrono::microseconds(n));
}
{
const long n = 1e3;
printf("Sleeping %ld milliseconds\n", n);
std::this_thread::sleep_for(std::chrono::milliseconds(n));
}
{
const time_t n = 1;
printf("Sleeping %ld seconds\n", n);
std::this_thread::sleep_for(std::chrono::seconds(n));
}
}
Outputs:
time ./cpp_sleeps
Sleeping 1000000000 nanoseconds
Sleeping 1000000 microseconds
Sleeping 1000 milliseconds
Sleeping 1 seconds
real 0m4.006s <!-- very close to 4 seconds
user 0m0.002s
sys 0m0.003s