Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pausing in C++ - Which Method?

I've noticed two different ways to "pause" in C++. (Though I think the proper name for it is sleeping.)

Method 1, (probably the method most are familiar with):

#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?

like image 454
Domani Tomlindo Avatar asked Dec 17 '22 20:12

Domani Tomlindo


1 Answers

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 (e.g. Linux, BSD, ...) but for example not on 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

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.

like image 110
Simon Plasger Avatar answered Dec 28 '22 10:12

Simon Plasger