Skip to content

Instantly share code, notes, and snippets.

@gaebor
Created June 21, 2018 00:20
Show Gist options
  • Save gaebor/44980fecb7674dd6ef1b93c42380ac5e to your computer and use it in GitHub Desktop.
Save gaebor/44980fecb7674dd6ef1b93c42380ac5e to your computer and use it in GitHub Desktop.
a lightweight progress indicator in c++11
#pragma once
#include <thread>
#include <chrono>
#include <cstdio>
#include <exception>
template<class Exception = std::exception, typename T1, typename T2, typename Func, typename ...Args>
void ProgressIndicator(T1 begin, T2* p, double total, const char* fmt,
bool enable, const Func& f, Args&&... args)
{
bool run = true;
double factor = 100.0 / total;
std::thread progress;
if (enable)
{
progress = std::thread([&]()
{
bool written = false;
while (run)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
if (run)
{
written = true;
fprintf(stderr, fmt, size_t(*p - begin)*factor);
fflush(stderr);
}
}
fprintf(stderr, fmt, size_t(*p - begin)*factor);
fflush(stderr);
});
}
try
{
f(args...);
}
catch (const Exception& e)
{
run = false;
if (progress.joinable())
progress.join();
throw e;
}
run = false;
if (progress.joinable())
progress.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment