72 lines
1.8 KiB
C++
72 lines
1.8 KiB
C++
#ifndef CPP_PROGRESS_HPP
|
|
#define CPP_PROGRESS_HPP
|
|
|
|
#include <iostream>
|
|
#include <cassert>
|
|
#include <cstdint>
|
|
|
|
namespace progress
|
|
{
|
|
class ProgressBar
|
|
{
|
|
public:
|
|
ProgressBar(const std::string &desc, const int64_t total_ticks, const int64_t bar_width = 50, const int64_t ticks_per_display = 1) : desc{desc}, total_ticks{total_ticks}, bar_width{bar_width}, ticks_per_display{ticks_per_display}
|
|
{
|
|
assert(total_ticks > 0 && bar_width > 0 && ticks_per_display > 0);
|
|
}
|
|
|
|
void tick_display()
|
|
{
|
|
#ifdef SHOW_PROGRESS_BAR
|
|
if (++ticks == total_ticks)
|
|
{
|
|
done();
|
|
return;
|
|
}
|
|
double progress = static_cast<double>(ticks) / total_ticks;
|
|
int64_t pos = static_cast<int64_t>(bar_width * progress);
|
|
display(pos);
|
|
#endif
|
|
}
|
|
|
|
private:
|
|
std::string get_bar(const int64_t pos)
|
|
{
|
|
if (bar != "" && pos == now_pos)
|
|
return bar;
|
|
bar.clear();
|
|
for (int i = 0; i < bar_width; ++i)
|
|
{
|
|
if (i < pos)
|
|
bar += '=';
|
|
else if (i == pos)
|
|
bar += ">";
|
|
else
|
|
bar += ' ';
|
|
}
|
|
now_pos = pos;
|
|
return bar;
|
|
}
|
|
|
|
void display(int64_t pos)
|
|
{
|
|
std::cout << "\33[2K\r" << "[" << get_bar(pos) << "]" << desc << std::flush;
|
|
}
|
|
|
|
void done()
|
|
{
|
|
display(bar_width);
|
|
std::cout << std::endl;
|
|
}
|
|
|
|
int64_t ticks = 0;
|
|
int64_t now_pos = -1;
|
|
std::string bar = "";
|
|
std::string desc = "";
|
|
const int64_t total_ticks;
|
|
const int64_t bar_width;
|
|
int64_t ticks_per_display;
|
|
};
|
|
}
|
|
|
|
#endif |