Skip to content

Commit

Permalink
relaxed memory order
Browse files Browse the repository at this point in the history
  • Loading branch information
karasikov committed Jun 12, 2020
1 parent 4f07db0 commit eb87c55
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
15 changes: 8 additions & 7 deletions progress_bar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ ProgressBar::ProgressBar(uint64_t total,

description_.resize(kMessageSize, ' ');

ShowProgress();
ShowProgress(0);
}

ProgressBar::~ProgressBar() {
Expand Down Expand Up @@ -120,14 +120,14 @@ std::string get_progress_summary(double progress_ratio) {
return buffer;
}

void ProgressBar::ShowProgress() const {
void ProgressBar::ShowProgress(uint64_t progress) const {
if (silent_)
return;

std::lock_guard<std::mutex> lock(mu_);

// calculate percentage of progress
double progress_ratio = total_ ? static_cast<double>(progress_) / total_
double progress_ratio = total_ ? static_cast<double>(progress) / total_
: 1.0;
assert(progress_ratio >= 0.0);
assert(progress_ratio <= 1.0);
Expand All @@ -142,7 +142,7 @@ void ProgressBar::ShowProgress() const {
os << std::put_time(std::localtime(&time), "[%F %T.")
<< std::setfill('0') << std::setw(3) << ms.count() << "]\t"
<< get_progress_summary(progress_ratio)
<< ", " + std::to_string(progress_) + "/" + std::to_string(total_) + '\n';
<< ", " + std::to_string(progress) + "/" + std::to_string(total_) + '\n';
*out << os.str() << std::flush;
return;
}
Expand All @@ -163,7 +163,7 @@ void ProgressBar::ShowProgress() const {
+ std::string(size_t(bar_size * progress_ratio), unit_bar_)
+ std::string(bar_size - size_t(bar_size * progress_ratio), unit_space_)
+ "] " + get_progress_summary(progress_ratio)
+ ", " + std::to_string(progress_) + "/" + std::to_string(total_) + '\r';
+ ", " + std::to_string(progress) + "/" + std::to_string(total_) + '\r';

*out << buffer_ << std::flush;

Expand All @@ -182,15 +182,16 @@ ProgressBar& ProgressBar::operator+=(uint64_t delta) {
if (silent_ || !delta)
return *this;

uint64_t after_update = (progress_ += delta);
uint64_t after_update
= progress_.fetch_add(delta, std::memory_order_relaxed) + delta;

assert(after_update <= total_);

// determines whether to update the progress bar from frequency_update
if (after_update == total_
|| (after_update - delta) / frequency_update
< after_update / frequency_update)
ShowProgress();
ShowProgress(after_update);

return *this;
}
2 changes: 1 addition & 1 deletion progress_bar.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class ProgressBar {
ProgressBar(const ProgressBar &) = delete;
ProgressBar& operator=(const ProgressBar &) = delete;

void ShowProgress() const;
void ShowProgress(uint64_t progress) const;
int GetConsoleWidth() const;
int GetBarLength() const;

Expand Down

0 comments on commit eb87c55

Please sign in to comment.