Advertisement
chevengur

СПРИНТ № 6 | Профилируем и ускоряем | Урок 4: Упрощаем логирование

Mar 14th, 2024 (edited)
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.14 KB | None | 0 0
  1. #include <chrono>
  2. #include <cstdlib>
  3. #include <iostream>
  4. #include <vector>
  5. #include "log_duration.h"
  6.  
  7. using namespace std;
  8.  
  9. vector<int> ReverseVector(const vector<int>& source_vector) {
  10.     vector<int> res;
  11.     for (int i : source_vector) {
  12.         res.insert(res.begin(), i);
  13.     }
  14.  
  15.     return res;
  16. }
  17.  
  18. int CountPops(const vector<int>& source_vector, int begin, int end) {
  19.     int res = 0;
  20.  
  21.     for (int i = begin; i < end; ++i) {
  22.         if (source_vector[i]) {
  23.             ++res;
  24.         }
  25.     }
  26.  
  27.     return res;
  28. }
  29.  
  30. void AppendRandom(vector<int>& v, int n) {
  31.     for (int i = 0; i < n; ++i) {
  32.         // получаем случайное число с помощью функции rand.
  33.         // с помощью (rand() % 2) получим целое число в диапазоне 0..1.
  34.         // в C++ имеются более современные генераторы случайных чисел,
  35.         // но в данном уроке не будем их касаться
  36.         v.push_back(rand() % 2);
  37.     }
  38. }
  39.  
  40. void Operate() {
  41.     {
  42.         LogDuration log_operate("Total");
  43.  
  44.         vector<int> random_bits;
  45.  
  46.         // операция << для целых чисел это сдвиг всех бит в двоичной
  47.         // записи числа. Запишем с её помощью число 2 в степени 17 (131072)
  48.         static const int N = 1 << 17;
  49.  
  50.         // заполним вектор случайными числами 0 и 1
  51.         {
  52.             LogDuration log("Append random");
  53.             AppendRandom(random_bits, N);
  54.         }
  55.  
  56.         vector<int> reversed_bits;
  57.         // перевернём вектор задом наперёд
  58.         {
  59.             LogDuration log_reverse("Reverse");
  60.             reversed_bits = ReverseVector(random_bits);
  61.         }
  62.  
  63.         {
  64.             LogDuration log_counting("Counting");
  65.             for (int i = 1, step = 1; i <= N; i += step, step *= 2) {
  66.                 double rate = CountPops(reversed_bits, 0, i) * 100. / i;
  67.                 cout << "After "s << i << " bits we found "s << rate << "% pops"s << endl;
  68.             }
  69.         }
  70.     }
  71. }
  72.  
  73. int main() {
  74.      
  75.     Operate();
  76. }
  77.  
  78. ***************************************************************************************************************************************
  79.  
  80. log_duration.h
  81.  
  82. #pragma once
  83.  
  84. #include <chrono>
  85. #include <iostream>
  86. #include <string>
  87.  
  88. class LogDuration {
  89. public:
  90.     // заменим имя типа std::chrono::steady_clock
  91.     // с помощью using для удобства
  92.     using Clock = std::chrono::steady_clock;
  93.  
  94.     LogDuration(const std::string name): name_operation_(name) {
  95.     }
  96.  
  97.     ~LogDuration() {
  98.         using namespace std::chrono;
  99.         using namespace std::literals;
  100.  
  101.         const auto end_time = Clock::now();
  102.         const auto dur = end_time - start_time_;
  103.         std::cerr << name_operation_ << ": "s << duration_cast<milliseconds>(dur).count() << " ms"s << std::endl;
  104.     }
  105.  
  106. private:
  107.     const Clock::time_point start_time_ = Clock::now();
  108.     std::string name_operation_ = "none";
  109. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement