Created
June 21, 2018 00:20
-
-
Save gaebor/44980fecb7674dd6ef1b93c42380ac5e to your computer and use it in GitHub Desktop.
a lightweight progress indicator in c++11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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