Created
August 22, 2013 11:15
-
-
Save endJunction/6305964 to your computer and use it in GitHub Desktop.
timing of std::pow, sqrt, cbrt.
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
#include <algorithm> | |
#include <chrono> | |
#include <cmath> | |
#include <functional> | |
#include <iostream> | |
#include <random> | |
#include <vector> | |
using namespace std::placeholders; | |
static std::size_t const array_size = 1000000; | |
using array = std::array<double, array_size>; | |
array | |
random_array() | |
{ | |
std::random_device rd; | |
std::default_random_engine e(rd()); | |
std::uniform_real_distribution<double> uniform_rnd(0, 1); | |
array a; | |
std::generate(a.begin(), a.end(), std::bind(uniform_rnd, e)); | |
return a; | |
} | |
template <typename F> | |
void | |
time(F&& f, std::string const info) | |
{ | |
std::chrono::time_point<std::chrono::system_clock> start, end; | |
start = std::chrono::system_clock::now(); | |
f(); | |
end = std::chrono::system_clock::now(); | |
std::chrono::duration<double> elapsed_seconds = end-start; | |
std::cout << info << " : " << elapsed_seconds.count() << "s\n"; | |
} | |
int main() | |
{ | |
array a = random_array(); | |
time([&a]() | |
{ | |
std::for_each(a.cbegin(), a.cend(), | |
std::bind(std::pow<double, int>, _1, 2)); | |
}, | |
"^2 std::pow<double, int>" | |
); | |
time([&a]() | |
{ | |
std::for_each(a.cbegin(), a.cend(), | |
std::bind(std::pow<double, double>, _1, 2)); | |
}, | |
"^2 std::pow<double, double>" | |
); | |
time([&a]() | |
{ | |
std::for_each(a.cbegin(), a.cend(), | |
[](double const x) { return x*x; }); | |
}, | |
"^2 x*x" | |
); | |
time([&a]() | |
{ | |
std::for_each(a.cbegin(), a.cend(), | |
std::bind(std::pow<double, double>, _1, 0.5)); | |
}, | |
"sqrt std::pow<double, double>" | |
); | |
time([&a]() | |
{ | |
std::for_each(a.cbegin(), a.cend(), | |
sqrt); | |
}, | |
"sqrt std::sqrt<double>" | |
); | |
time([&a]() | |
{ | |
std::for_each(a.cbegin(), a.cend(), | |
std::bind(std::pow<double, double>, _1, 1./3)); | |
}, | |
"cbrt std::pow<double, double>" | |
); | |
time([&a]() | |
{ | |
std::for_each(a.cbegin(), a.cend(), | |
cbrt); | |
}, | |
"cbrt std::cbrt<double>" | |
); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment