C语言-sleep()、usleep()、nanosleep() 休眠函数 作者:马育民 • 2025-10-07 10:14 • 阅读:10001 # 介绍 让程序休眠(延时)指定的时间,然后再继续执行。是阻塞函数,调用期间当前线程会暂停执行,不消耗 CPU 资源,但会阻塞后续代码运行,需避免在实时性要求高的场景中使用过长延时 # 头文件 使用这些函数时,需要加上下面头文件才能调用: ``` #include ``` # sleep() 秒级延时 ### 定义 ``` unsigned int sleep (unsigned int __seconds); ``` **参数:** - `__seconds`:需要休眠的时间,单位:秒 **返回值**:成功返回 `0`;失败返回 `-1`(例如 `__seconds` 超过最大值)。 ### 例子 ``` #include #include int main() { printf("Hello, World!\n"); sleep(3); printf("Hello, World!\n"); return 0; } ``` # usleep() 微秒级延时 秒、毫秒、微秒、纳秒换算详见 [链接](https://www.malaoshi.top/show_1EFccBBcIEK.html "链接") ### 定义 ``` int usleep(unsigned int __useconds); ``` **参数:** - `__useconds`:需要休眠的时间,单位:微秒,范围通常为 `0` 到 `1,000,000`(即最大支持 1 秒延时,部分平台可能支持更大值)。 **返回值**:成功返回 `0`;失败返回 `-1`(例如 `usec` 超过最大值)。 # nanosleep() 纳秒级延时,精度最高(1微秒=1000纳秒) 秒、毫秒、微秒、纳秒换算详见 [链接](https://www.malaoshi.top/show_1EFccBBcIEK.html "链接") ### 定义 ``` int nanosleep(const struct timespec *req, struct timespec *rem); ``` **参数:** - `req`: `struct timespec` 类型指针,设置休眠的时间 - `rem`: 若 `remain` 不为 `NULL`,那么指针指向的缓冲区返回剩余的休眠时间 **返回值**:成功返回 `0`;失败返回 `-1` ### timespec结构体 ``` struct timespec { time_t tv_sec; /* 秒 */ long tv_nsec; /* 纳秒 范围是0-999999999(9个9)*/ }; ``` ### 例子 ``` #include #include int main(int argc, char *argv[]) { struct timespec s_sleep; struct timespec ns_sleep; s_sleep.tv_sec = 5; // 5秒 ns_sleep.tv_nsec = 999999999; // 约1秒 while(1) { nanosleep(&s_sleep, 0); printf("5 seconds passed...\n"); printf("\n"); nanosleep(&ns_sleep, 0); printf("1 seconds passed...\n"); printf("\n"); } return 0; } ``` 原文出处:http://malaoshi.top/show_1GW1zrHCcURH.html