vendredi 24 janvier 2014

That 123456 again

And why GMP C++ interface is so slow...
#include <iostream>
#include <ctime>
#include <gmpxx.h>
typedef mpz_class Integer;
Integer N[] = {1, 12, 123, 1234, 12345, 123456};
Integer sum_digits(Integer n);
Integer factorial(Integer n);
int main(int argc, char *argv[])
{
Integer res = 0;
std::clock_t start = std::clock();
for(int i = 0; i < sizeof(N)/sizeof(Integer); ++i)
{
res += sum_digits(factorial(N[i]));
}
std::cout << res << std::endl;
std::clock_t end = std::clock();
std::cout << "Execution time: "
<< 1e3 * ((double) (end - start)) / CLOCKS_PER_SEC
<< " ms" << std::endl;
}
Integer factorial(Integer n)
{
Integer res = 1;
for(Integer k = n; k > 1; k -= 1)
res *= k;
return res;
}
Integer sum_digits(Integer n)
{
Integer res = 0;
std::string s = n.get_str();
for(auto i = s.begin(); i != s.end(); ++i)
res += (int) *i - (int) '0';
return res;
}
view raw gmpxx_test.cxx hosted with ❤ by GitHub
alexey at daphne in tests$ clang++ gmp_test.cxx -lgmp -lgmpxx -std=c++11 -O3
alexey at daphne in tests$ ./a.out
2652733
Execution time: 8394.96 ms
alexey at daphne in tests$
view raw gistfile1.sh hosted with ❤ by GitHub
Even slower than Lisp. Or it's C++ itself?