如何在 c 中实现毫秒级的睡眠
本文介绍了在 c 中睡眠毫秒的方法。
使用 std::this_thread::sleep_for
方法在 c 中睡眠
这个方法是
库中 sleep
函数的纯 c 版本,它是 windows 和 unix 平台的可移植版本。为了更好地演示示例,我们暂停进程 3000 毫秒。
#include #include #include using std::cin;
using std::cout;
using std::endl;
using std::this_thread::sleep_for;
constexpr int time_to_sleep = 3000;
int main() {
cout << "started loop.." << endl;
for (int i = 0; i < 10; i) {
cout << "iteration - " << i << endl;
if (i == 4) {
cout << "sleeping ...." << endl;
sleep_for(std::chrono::milliseconds(time_to_sleep));
}
}
return 0;
}
输出:
started loop...
iteration - 0
iteration - 1
iteration - 2
iteration - 3
iteration - 4
sleeping ....
iteration - 5
iteration - 6
iteration - 7
iteration - 8
iteration - 9
我们可以使用 std::chono_literals
命名空间重写上面的代码,使其更有说服力。
#include #include using std::cin;
using std::cout;
using std::endl;
using std::this_thread::sleep_for;
using namespace std::chrono_literals;
int main() {
cout << "started loop.." << endl;
for (int i = 0; i < 10; i) {
cout << "iteration - " << i << endl;
if (i == 4) {
cout << "sleeping ...." << endl;
sleep_for(3000ms);
}
}
return 0;
}
在 c 中使用 usleep
函数进行睡眠
usleep
是在
头中定义的一个 posix 专用函数,它接受微秒数作为参数,它应该是无符号整数类型,能够容纳 [0,1000000]范围内的整数。
#include #include using std::cin;
using std::cout;
using std::endl;
constexpr int time_to_sleep = 3000;
int main() {
cout << "started loop.." << endl;
for (int i = 0; i < 10; i) {
cout << "iteration - " << i << endl;
if (i == 4) {
cout << "sleeping ...." << endl;
usleep(time_to_sleep * 1000);
;
}
}
return 0;
}
另外,我们也可以使用 usleep
函数定义一个自定义的宏,并做出一个更可重用的代码片段。
#include #include #define sleep_ms(milsec) usleep(milsec * 1000)
using std::cin;
using std::cout;
using std::endl;
constexpr int time_to_sleep = 3000;
int main() {
cout << "started loop.." << endl;
for (int i = 0; i < 10; i) {
cout << "iteration - " << i << endl;
if (i == 4) {
cout << "sleeping ...." << endl;
sleep_ms(time_to_sleep);
}
}
return 0;
}
使用 nanosleep
函数在 c 中休眠
nanosleep
函数是另一个 posix 特定版本,它提供了更好的处理中断的功能,并且对睡眠间隔有更精细的分辨率。也就是说,程序员创建一个 timespec
结构,分别指定秒数和纳秒数。nanosleep
也会取第二个 timespec
结构参数来返回剩余的时间间隔,以防程序被信号打断。注意,中断处理由程序员负责。
#include #include using std::cin;
using std::cout;
using std::endl;
constexpr int secs_to_sleep = 3;
constexpr int nsec_to_sleep = 3;
int main() {
struct timespec request {
secs_to_sleep, nsec_to_sleep
}, remaining{secs_to_sleep, nsec_to_sleep};
cout << "started loop.." << endl;
for (int i = 0; i < 10; i) {
cout << "iteration - " << i << endl;
if (i == 4) {
cout << "sleeping ...." << endl;
nanosleep(&request, &remaining);
}
}
return 0;
}
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:c
-
可以通过使用复位按钮,softwarereset 库和 adafruit sleepydog 库来复位 arduino。
发布时间:2024/03/13 浏览次数:181 分类:c
-
可以使用简单的方法 toint()函数和 serial.parseint()函数将 char 转换为 int。
发布时间:2024/03/13 浏览次数:151 分类:c
-
可以使用 arduino 中的循环制作计数器。