Date: 2025jun16
Language: C/C++
Q. C/C++: How to sleep for nanoseconds, microseconds, milliseconds, seconds
A. Here is how to do it in C. This works in C++ but its better to use chrono
for new code.
#include <stdio.h>
#include <unistd.h>
#include <time.h>
static const long NANOSEC = 1000000000;
void sleep_nanoseconds(const long nanoseconds) {
struct timespec ts = { 0, nanoseconds };
if (nanoseconds > 999999999) {
ts.tv_sec = nanoseconds / NANOSEC;
ts.tv_nsec = nanoseconds % NANOSEC;
}
nanosleep(&ts);
}
void sleep_microseconds(const useconds_t microseconds) {
usleep(microseconds);
}
void sleep_milliseconds(const long milliseconds) {
usleep(milliseconds * 1000);
}
void sleep_seconds(const time_t seconds) {
sleep(seconds);
}
int main() {
{
const long n = 1e9;
printf("Sleeping %ld nanoseconds\n", n);
sleep_nanoseconds(n);
}
{
const useconds_t n = 1e6;
printf("Sleeping %ld microseconds\n", n);
sleep_microseconds(n);
}
{
const long n = 1e3;
printf("Sleeping %ld milliseconds\n", n);
sleep_milliseconds(n);
}
{
const time_t n = 1;
printf("Sleeping %ld seconds\n", n);
sleep_seconds(n);
}
}
There is also g_usleep() if you're using GLib.
Outputs:
$ time c_sleeps.c
Sleeping 1000000000 nanoseconds
Sleeping 1000000 microseconds
Sleeping 1000 milliseconds
Sleeping 1 seconds
real 0m4.003s <!-- almost exactly 4 seconds
user 0m0.001s
sys 0m0.002s