Playing around with the boost multiprecision library. Calculating some big factorial numbers and such.
Problem is the output takes too long. 100,000! takes 0.5 seconds to calculate and 11 seconds to print. 1,000,000! takes half an hour (yes the output only).
Using cout for the output with > to put it to a file: ./prg > file
Tried putting it to a string first, stringstream, normal cout. Everything the same.
The convertion to a string just takes very long. Is there any way to speed it up?
Code example:
#include <iostream>
#include <chrono>
#include <string>
#include <boost/multiprecision/cpp_int.hpp>
int main() {
uint32_t num = 100000;
boost::multiprecision::cpp_int result = 1;
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
for (uint32_t i = 2; i <= num; i++) {
result *= i;
}
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << "calculation: " << std::chrono::duration_cast<std::chrono::milliseconds> (end - begin).count() / 1000.0 << " sec" << std::endl;
std::string s = result.str();
std::chrono::steady_clock::time_point endOutput = std::chrono::steady_clock::now();
std::cout << "toString: " << std::chrono::duration_cast<std::chrono::milliseconds> (endOutput - end).count() / 1000.0 << " sec" << std::endl;
std::cout << "length: " << s.length() << std::endl;
return 0;
}
output:
calculation: 1.014 sec
toString: 7.643 sec
length: 456574
output same code in java using BigInteger:
calculation: 2.646 sec
toString: 0.466 sec
length: 456574
I was going to recommend you post a self-answer. But then I had this crammed into a single comment:
So I figured that I might as well post it here for added value of demonstration code.
Modernizing The Repro
We can express that program a lot cleaner:
Which may print something like
More Comparative Benchmarks
To see how much better
mpz_int
may perform, let's compare them:Live On Wandbox
Which may print something like
As you can see GMP is orders of magnitude more optimized (~200x faster for the
str()
operation in my test run)