-
Notifications
You must be signed in to change notification settings - Fork 11
/
ProgressBar.h
101 lines (76 loc) · 2.71 KB
/
ProgressBar.h
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* @file UtilitiesLib/ProgressBar.h
* @date Nov 30, 2018
* @author Bernd Doser, HITS gGmbH
*/
#pragma once
#include <chrono>
#include <iostream>
#include "UtilitiesLib/pink_exception.h"
namespace pink {
class ProgressBar
{
public:
ProgressBar(int total, int width, int number_of_progress_prints = 10, std::ostream& os = std::cout)
: total(total < 1 ? throw pink::exception("ProgressBar: total must be larger than 0") : total),
width(width < number_of_progress_prints ? throw pink::exception("ProgressBar: width must be larger than number of progress prints") : width),
number_of_progress_prints(number_of_progress_prints < 0 ? throw pink::exception("ProgressBar: width must be equal or larger than 0") : number_of_progress_prints),
number_of_ticks_in_section(total / number_of_progress_prints),
remaining_ticks_in_section(total % number_of_progress_prints),
os(os),
next_valid_tick(number_of_ticks_in_section + (remaining_ticks_in_section ? 1 : 0))
{}
void operator ++ ()
{
if (end_reached) return;
if (ticks == total)
{
end_reached = true;
return;
}
if (ticks == next_valid_tick)
{
next_valid_tick += number_of_ticks_in_section;
}
++ticks;
if (ticks == next_valid_tick)
{
int pos = width * ticks / total;
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time).count();
os << "[";
for (int i = 0; i < width; ++i) {
if (i < pos) os << '=';
else if (i == pos) os << ">";
else os << ' ';
}
os << "] " << static_cast<int>(100.0 * ticks / total) << " % " << time_elapsed / 1000.0 << " s" << std::endl;
if (ticks == total) os << std::endl;
else os << std::flush;
}
}
bool valid() const
{
return ticks == next_valid_tick;
}
private:
int ticks = 0;
/// Total number of tasks
int total;
/// Number of characters of progress bar
int width;
/// Number of progress informations should be printed
int number_of_progress_prints;
/// Number of ticks between progress stages
int number_of_ticks_in_section;
/// Number of remaining ticks
int remaining_ticks_in_section;
/// Current progress number
std::ostream& os;
/// Flag end was reached
bool end_reached = false;
///
int next_valid_tick;
std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
};
} // namespace pink