[英]Pausing in C++ - Which Method?
I've noticed two different ways to "pause" in C++. 我注意到有两种不同的方法可以在C ++中“暂停”。 (Though I think the proper name for it is sleep
ing.) (虽然我认为它的正确名称是sleep
。)
Method 1, (probably the method most are familiar with): 方法1,(可能是最熟悉的方法):
#include <iostream>
#include <unistd.h>
int main() {
std::cout<<"Hello, "<<std::endl;
sleep(1);
std::cout<<"world!\n";
return 0;
}
And the method I learned first: 我首先学到的方法:
#include <iostream>
#include <thread>
#include <chrono>
int main() {
std::cout<<"Hello, "<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout<<"world!\n";
return 0;
}
I'm not asking which way is right , (they both do the same thing), but rather I'm asking which is more used , or "accepted" . 我不是问哪条路是对的 ,(它们都做同样的事情),而是我要问哪个更常用 ,或者“接受” 。 Also, is there a difference between these two when it comes to things like speed/performance? 另外,这两者在速度/性能等方面有区别吗?
The difference between these two methods is the portability: 这两种方法的区别在于可移植性:
sleep
from unistd.h
is part of the C POSIX Library and therefore only available on Systems that provide the POSIX-API (eg Linux, BSD, ...) but for example not on Windows 来自unistd.h
sleep
是C POSIX库的一部分,因此只能在提供POSIX-API的系统上使用(例如Linux,BSD,...),但不能在Windows上使用
std::this_thread::sleep_for
is part of the C++ Standard Library (since C++11) and is therefore available on all platforms that support C++11 and newer std::this_thread::sleep_for
是C ++标准库的一部分(自C ++ 11以来),因此可在支持C ++ 11及更高版本的所有平台上使用
If you have the choice use std::this_thread::sleep_for
to rely only on a C++11 implementation and not on the System API. 如果您可以选择使用std::this_thread::sleep_for
仅依赖于C ++ 11实现而不依赖于System API。
Primary differences: 主要差异:
std::this_thread::sleep_for
is a standard function (since C++11). std::this_thread::sleep_for
是一个标准函数(自C ++ 11以来)。 sleep
is a POSIX standard function, and so is only available on systems that support POSIX. sleep
是POSIX标准函数,因此仅在支持POSIX的系统上可用。 sleep
is seconds, while std::this_thread::sleep_for
allows the use of any std::chrono::duration
(although the clock used for measurement will have its own granlarity that may be less precise than the time that you specify). sleep
参数的单位是秒,而std::this_thread::sleep_for
允许使用任何std::chrono::duration
std::this_thread::sleep_for
std::chrono::duration
(尽管用于测量的时钟将具有自己的粒度,可能不如时间精确你指定的)。 std::this_thread::sleep_for
is not defined in relation to signals that may interrput program flow. std::this_thread::sleep_for
的行为未定义与可能会干扰程序流的信号有关。 Typically, std::this_thread::sleep_for
will be interrupted prematurely just like sleep
would be, but there is no easy way of finding out how much time was left to sleep. 通常情况下, std::this_thread::sleep_for
会像sleep
那样过早地中断,但是没有简单的方法可以找出剩下多少时间来睡觉。 sleep
on the other hand returns the time left to sleep, so it is easy to deal with interruptions using a loop that sleeps until returned time to sleep is zero. sleep
,另一方面返回剩余时间睡觉,所以很容易对付使用一个循环,休眠,直到回到睡觉的时间是零中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.