progress_bar.hpp 1.27 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// == file : progress_bar.hpp
// == author : Pierre Esterie
#ifndef TIMIT_UTILS_PROGRESS_BAR_HPP
#define TIMIT_UTILS_PROGRESS_BAR_HPP

#include <sstream>
#include <memory>
#include <thread>
#include <iostream>

namespace timit { namespace utils
{
  template<typename Object>
  int progress(Object& obj);

  struct progress_bar {
    std::stringstream sstr{};
    std::thread t;

    template<typename Object>
    void follow(Object& obj) {
        this->t = std::thread(
            [this, &obj]() {
                bool run = true;
                while(run) {
                    sstr.str("");
                    sstr.clear();
                    sstr.precision(4);
                    int p = timit::utils::progress(obj);
                    std::cout << p << std::endl;
                    sstr << "[";
                    for(int i = 0; i < 100; ++i) 
                    {
                      sstr << (i < p ? "\u2038" : " ");
                    }
                    sstr << "] " << p << "%    ";
                    std::cout << '\r' << sstr.str() << std::flush;
                    run =  p < 100;
                    std::this_thread::sleep_for(std::chrono::milliseconds(200));
                }
            });
    }

    void finish() {
        this->t.join();
    }
  };
}}
#endif