C Program to show Sleep() function example.

This C program demonstrates the sleep() function, which pauses (delays) the execution of your program for a set amount of time. This is handy for animations, retry loops, timed messages, or simply slowing a program down so you can watch what it does. Because the function differs between operating systems, this tutorial gives you one portable program that works on Windows, Linux and macOS.

Important: The Units Are Different!

A very common mistake is getting the time unit wrong. They are not the same across systems:

Function Header Platform Unit
Sleep(ms) <windows.h> Windows milliseconds
sleep(sec) <unistd.h> Linux / macOS seconds
usleep(us) <unistd.h> Linux / macOS microseconds

So Sleep(1000) on Windows waits one second (1000 ms), while sleep(1) on Linux also waits one second. (Older tutorials that call this “microseconds” are simply wrong.)

The Program (Portable)

#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

int main(void)
{
    printf("Message before the pause...\n");
    fflush(stdout);   /* force output to appear before we sleep */

#ifdef _WIN32
    Sleep(2000);      /* Windows: milliseconds -> 2000 ms = 2 seconds */
#else
    sleep(2);         /* Linux / macOS: seconds */
#endif

    printf("Message after a 2-second pause.\n");
    return 0;
}

How the Program Works

  • The #ifdef _WIN32 block picks the right header and function for the platform automatically, so the same source compiles everywhere.
  • fflush(stdout) forces the first message to print before the pause — otherwise it might sit in the output buffer until the program ends.
  • The program prints a message, waits two seconds, then prints again. This replaces the old version that used the Windows-only <windows.h> and getch() and would not compile on Linux or macOS.

Sample Output

Message before the pause...
(2 second pause)
Message after a 2-second pause.

For a deeper understanding of the standard library and system calls, The C Programming Language by Kernighan and Ritchie is the classic reference — find it on Amazon.

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you.

Related C Programs

Because timing behaviour depends on your system, run this on a real local setup — see our guide to a complete C development environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>