A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
sleep suspends the calling thread for a specified number of seconds. usleep suspends for a specified number of microseconds. Both are POSIX functions declared in unistd.h, not part of the ISO C standard. On Windows, the equivalent is Sleep (capital S) from windows.h, which takes milliseconds. These functions are used for polling intervals, rate limiting, retry backoff, and giving hardware time to respond.
#include <stdio.h>#include <unistd.h>#include <time.h>int main(void) {printf("Starting...\n");fflush(stdout);clock_t start = clock();sleep(2);clock_t end = clock();printf("After sleep(2): CPU time elapsed = %.4f s\n",(double)(end - start) / CLOCKS_PER_SEC);start = clock();usleep(500000);end = clock();printf("After usleep(500000): CPU time elapsed = %.4f s\n",(double)(end - start) / CLOCKS_PER_SEC);return 0;}
The CPU time elapsed is nearly zero. The process was sleeping, not executing. clock() does not advance during sleep. The wall-clock time advanced by 2 seconds and 0.5 seconds respectively, but the CPU was idle. This is the key distinction: sleep yields the CPU to other processes. It is not a busy-wait. Your program consumes no CPU cycles while sleeping.
#include <stdio.h>#ifdef _WIN32#include <windows.h>#define sleep_ms(ms) Sleep(ms)#else#include <unistd.h>#define sleep_ms(ms) usleep((ms) * 1000)#endifint main(void) {printf("Waiting 1 second...\n");fflush(stdout);sleep_ms(1000);printf("Done.\n");return 0;}
The wrapper macro normalizes the API. Windows Sleep takes milliseconds. POSIX usleep takes microseconds. The macro converts milliseconds to the appropriate unit. This pattern appears in every cross-platform C project that needs timed delays.
usleep is marked obsolete in POSIX.1-2008. The modern replacement is nanosleep, which offers nanosecond precision and better signal handling. For new POSIX code, prefer nanosleep. For simple delays, usleep still works everywhere and is unlikely to be removed.
Sleep functions are the simplest form of concurrency control: do nothing for a while. They appear in retry loops, heartbeat timers, and hardware polling. Use them instead of busy-wait loops. Your CPU will thank you. Next: div, which returns both quotient and remainder from a single integer division.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.