osrm-backend/include/util/percent.hpp

94 lines
2.0 KiB
C++
Raw Normal View History

#ifndef PERCENT_HPP
#define PERCENT_HPP
2014-05-20 17:58:32 -04:00
#include <atomic>
2016-05-27 15:05:04 -04:00
#include <iostream>
#include "util/isatty.hpp"
#include "util/log.hpp"
2016-01-05 10:51:13 -05:00
namespace osrm
{
namespace util
{
2014-05-07 12:39:16 -04:00
class Percent
{
Log &log;
2014-05-07 12:39:16 -04:00
public:
explicit Percent(Log &log_, unsigned max_value, unsigned step = 5) : log{log_}
{
Reinit(max_value, step);
}
// Reinitializes
2016-04-28 18:46:59 -04:00
void Reinit(unsigned max_value, unsigned step = 5)
2014-05-07 12:39:16 -04:00
{
m_max_value = max_value;
m_current_value = 0;
m_percent_interval = m_max_value / 100;
m_next_threshold = m_percent_interval;
m_last_percent = 0;
m_step = step;
}
2014-05-07 12:39:16 -04:00
// If there has been significant progress, display it.
2016-04-28 18:46:59 -04:00
void PrintStatus(unsigned current_value)
2014-05-07 12:39:16 -04:00
{
if (current_value >= m_next_threshold)
{
m_next_threshold += m_percent_interval;
2016-04-28 18:46:59 -04:00
PrintPercent(current_value / static_cast<double>(m_max_value) * 100.);
}
2014-05-07 12:39:16 -04:00
if (current_value + 1 == m_max_value)
log << " 100%";
}
2016-04-28 18:46:59 -04:00
void PrintIncrement()
2014-05-07 12:39:16 -04:00
{
++m_current_value;
2016-04-28 18:46:59 -04:00
PrintStatus(m_current_value);
}
2016-04-28 18:46:59 -04:00
void PrintAddition(const unsigned addition)
2014-05-07 12:39:16 -04:00
{
m_current_value += addition;
2016-04-28 18:46:59 -04:00
PrintStatus(m_current_value);
}
2014-05-07 12:39:16 -04:00
private:
2014-05-20 17:58:32 -04:00
std::atomic_uint m_current_value;
2014-05-07 12:39:16 -04:00
unsigned m_max_value;
unsigned m_percent_interval;
unsigned m_next_threshold;
unsigned m_last_percent;
unsigned m_step;
// Displays progress.
2016-04-28 18:46:59 -04:00
void PrintPercent(double percent)
2014-05-07 12:39:16 -04:00
{
while (percent >= m_last_percent + m_step)
{
m_last_percent += m_step;
if (m_last_percent % 10 == 0)
{
log << " " << m_last_percent << "% ";
}
2014-05-07 12:39:16 -04:00
else
{
log << ".";
}
// When not on a TTY, print newlines after each progress indicator so
// so that progress is visible to line-buffered logging systems
if (!IsStdoutATTY())
2017-09-15 04:45:07 -04:00
log << std::endl;
}
}
};
2016-01-05 10:51:13 -05:00
}
}
#endif // PERCENT_HPP