Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- log_duration.h
- #pragma once
- #include <chrono>
- #include <iostream>
- #define PROFILE_CONCAT_INTERNAL(X, Y) X##Y
- #define PROFILE_CONCAT(X, Y) PROFILE_CONCAT_INTERNAL(X, Y)
- #define UNIQUE_VAR_NAME_PROFILE PROFILE_CONCAT(profileGuard, __LINE__)
- #define LOG_DURATION(x) LogDuration UNIQUE_VAR_NAME_PROFILE(x)
- class LogDuration {
- public:
- // заменим имя типа std::chrono::steady_clock
- // с помощью using для удобства
- using Clock = std::chrono::steady_clock;
- LogDuration(const std::string& id) : id_(id) {
- }
- ~LogDuration() {
- using namespace std::chrono;
- using namespace std::literals;
- const auto end_time = Clock::now();
- const auto dur = end_time - start_time_;
- std::cerr << id_ << ": "s << duration_cast<milliseconds>(dur).count() << " ms"s << std::endl;
- }
- private:
- const std::string id_;
- const Clock::time_point start_time_ = Clock::now();
- };
- ***************************************************************************************************************************************
- main.cpp
- #include <chrono>
- #include <cstdlib>
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include "log_duration.h"
- using namespace std;
- vector<int> ReverseVector(const std::vector<int>& source_vector) {
- std::vector<int> res(source_vector.size());
- std::reverse_copy(source_vector.begin(), source_vector.end(), res.begin());
- return res;
- }
- int CountPops(const vector<int>& source_vector, int begin, int end) {
- int res = 0;
- for (int i = begin; i < end; ++i) {
- if (source_vector[i]) {
- ++res;
- }
- }
- return res;
- }
- void AppendRandom(vector<int>& v, int n) {
- v.reserve(n);
- for (int i = 0; i < n; ++i) {
- // получаем случайное число с помощью функции rand.
- // с помощью (rand() % 2) получим целое число в диапазоне 0..1.
- // в C++ имеются более современные генераторы случайных чисел,
- // но в данном уроке не будем их касаться
- v.push_back(rand() % 2);
- }
- }
- void Operate() {
- {
- LOG_DURATION("Total");
- vector<int> random_bits;
- // операция << для целых чисел это сдвиг всех бит в двоичной
- // записи числа. Запишем с её помощью число 2 в степени 17 (131072)
- static const int N = 1 << 17;
- // заполним вектор случайными числами 0 и 1
- {
- LOG_DURATION("Append random");
- AppendRandom(random_bits, N);
- }
- vector<int> reversed_bits;
- // перевернём вектор задом наперёд
- {
- LOG_DURATION("Reverse");
- reversed_bits = ReverseVector(random_bits);
- }
- {
- LOG_DURATION("Counting");
- for (int i = 1, step = 1; i <= N; i += step, step *= 2) {
- double rate = CountPops(reversed_bits, 0, i) * 100. / i;
- cout << "After "s << i << " bits we found "s << rate << "% pops"s << endl;
- }
- }
- }
- }
- int main() {
- Operate();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement