Skip to content

Instantly share code, notes, and snippets.

@nekko1119
Last active December 23, 2015 10:19
Show Gist options
  • Save nekko1119/6620985 to your computer and use it in GitHub Desktop.
Save nekko1119/6620985 to your computer and use it in GitHub Desktop.
処理を別スレッドで行い、メインスレッドは進捗をパーセント表示する。大きい数にも対応したくてBoost.Multiprecisionを使ったせいでコードが複雑になった感。変数iとnの読み書きがスレッドセーブじゃない気がする…
#include <future>
#include <iostream>
#include <chrono>
#include <thread>
#include <string>
#include <algorithm>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
boost::multiprecision::cpp_int simple(boost::multiprecision::cpp_int& n, int& i)
{
boost::multiprecision::cpp_int sum = 0;
for (i = 0; i <= n; ++i)
{
sum += i;
}
return sum;
}
boost::multiprecision::cpp_int effective(boost::multiprecision::cpp_int& n, int& i)
{
return (1 + n) * n / 2;
}
int main()
{
boost::multiprecision::cpp_int n = 0;
std::string buf;
std::cout << "[1, n]までの自然数列の和を求めます\n";
do
{
std::cout << ">";
std::getline(std::cin, buf);
try
{
n.assign(buf);
}
catch (...)
{
}
buf.clear();
} while (n < 2);
int i = 0;
std::future<boost::multiprecision::cpp_int> f = std::async(simple, std::ref(n), std::ref(i));
std::cout << "処理中\n";
do
{
boost::multiprecision::cpp_dec_float_100 fl(n.str());
fl += 1.0;
fl = i / fl;
fl *= 100;
auto work = fl.str();
auto first = std::find(work.begin(), work.end(), '.');
work.erase(first, work.end());
std::cout << "\r";
std::cout << boost::multiprecision::cpp_int(work) << "%";
} while (std::future_status::ready != f.wait_for(std::chrono::milliseconds(0)));
std::cout << std::endl;
auto sum = f.get();
std::cout << "処理完了!" << std::endl;
std::cout << "合計は" << sum << "です" << std::endl;
auto f2 = std::async(effective, std::ref(n), std::ref(i));
std::cout << "(効率的な方法で計算" << f2.get() << ")\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment