Advertisement
chevengur

СПРИНТ № 6 | Потоковые хитрости | Урок 3: Связь потоков: в поисках оптимального ввода и вывода

Mar 28th, 2024
718
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. log_duration.h
  2.  
  3. #pragma once
  4.  
  5. #include <chrono>
  6. #include <iostream>
  7.  
  8. using namespace std;
  9. using namespace chrono;
  10. using namespace literals;
  11.  
  12. #define PROFILE_CONCAT_INTERNAL(X, Y) X##Y
  13. #define PROFILE_CONCAT(X, Y) PROFILE_CONCAT_INTERNAL(X, Y)
  14. #define UNIQUE_VAR_NAME_PROFILE PROFILE_CONCAT(profileGuard, __LINE__)
  15. #define LOG_DURATION(x) LogDuration UNIQUE_VAR_NAME_PROFILE(x)
  16.  
  17. class LogDuration {
  18. public:
  19.     LogDuration(const std::string& id) : id_(id) {
  20.     }
  21.  
  22.     ~LogDuration() {
  23.         const auto end_time = steady_clock::now();
  24.         const auto dur = end_time - start_time_;
  25.         cerr << id_ << ": "s << duration_cast<milliseconds>(dur).count() << " ms"s << endl;
  26.     }
  27.  
  28. private:
  29.     const std::string id_;
  30.     const steady_clock::time_point start_time_ = steady_clock::now();
  31. };
  32.  
  33. ***************************************************************************************************************************************
  34. main.cpp
  35.  
  36. #include "log_duration.h"
  37.  
  38. #include <iostream>
  39.  
  40. using namespace std;
  41.  
  42. class StreamUntier {
  43. public:
  44.  
  45.     StreamUntier(istream& cin): stream(cin)
  46.     {
  47.         tied_before_ = stream.tie(nullptr);
  48.     }
  49.  
  50.     ~StreamUntier()
  51.     {
  52.         stream.tie(tied_before_);
  53.     }
  54.  
  55. private:
  56.     istream& stream;
  57.     ostream* tied_before_;
  58. };
  59.  
  60. int main() {
  61.     LOG_DURATION("\\n with tie"s);
  62.  
  63.     StreamUntier guard(cin);
  64.     int i;
  65.     while (cin >> i) {
  66.         cout << i * i << "\n"s;
  67.     }
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement