From c748e1ed7c9693931ae9ee61cf7c45aee2305728 Mon Sep 17 00:00:00 2001 From: KunoiSayami Date: Wed, 10 May 2023 00:57:26 +0800 Subject: feat: Use thread to show progress Signed-off-by: KunoiSayami --- normal_distribution.cpp | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/normal_distribution.cpp b/normal_distribution.cpp index 93aff27..20ef61c 100644 --- a/normal_distribution.cpp +++ b/normal_distribution.cpp @@ -1,8 +1,10 @@ #include #include +#include #include #include #include +#include #include inline void @@ -37,6 +39,18 @@ void checkFileValid(const std::string &name, size_t length) { } } +void progress_bar(const std::set &v, size_t length) { + size_t previous_rate = 0; + while (v.size() < length) { + fprintf(stderr, "\rProgress %.02f%%(%lu) rate: %lu/s", + (double)v.size() * 100 / (double)length, v.size(), + v.size() - previous_rate); + previous_rate = v.size(); + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + fputs("", stderr); +} + int main(int argc, char const *argv[]) { if (argc == 3) { @@ -67,17 +81,17 @@ int main(int argc, char const *argv[]) { vector.reserve(length); + std::thread progress_tl(progress_bar, std::ref(set), length); + while (set.size() != length) { auto element = (long long)std::round(normalDistribution(randomEngine)); auto ret = set.insert(element); if (ret.second) { vector.push_back(element); - - fprintf(stderr, "\rProgress %.02f%% %lu", - (double)set.size() * 100 / (double)length, set.size()); } } - fputs("", stderr); + + progress_tl.join(); assert(vector.size() == length); -- cgit v1.3.1