Created
June 25, 2015 03:12
-
-
Save greenbagels/04a5ef1f3af1af81fd96 to your computer and use it in GitHub Desktop.
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 <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <chrono> | |
template<typename T> | |
T sum_for_each(std::vector<T> const& vec) | |
{ | |
T sum = 0; | |
std::for_each(vec.begin(), vec.end(), | |
[&sum](int const& n) { sum += n; }); | |
return sum; | |
} | |
template<typename T> | |
T sum_forloop(std::vector<T> const& vec) | |
{ | |
T sum = 0; | |
size_t const size = vec.size(); | |
for (size_t i=0; i<size; ++i) | |
sum += vec[i]; | |
return sum; | |
} | |
template<typename T> | |
T sum_accumulate(std::vector<T> const& vec) | |
{ | |
return std::accumulate(vec.begin(), vec.end(), 0); | |
} | |
int main() | |
{ | |
using namespace std::chrono; | |
std::vector<double> vec(6.2e7); | |
high_resolution_clock::time_point t1 = high_resolution_clock::now(); | |
auto sum1 = sum_forloop(vec); | |
high_resolution_clock::time_point t2 = high_resolution_clock::now(); | |
size_t duration = duration_cast<microseconds>( t2 - t1 ).count(); | |
std::cout << "forloop " << duration << std::endl; | |
t1 = high_resolution_clock::now(); | |
auto sum2 = sum_for_each(vec); | |
t2 = high_resolution_clock::now(); | |
duration = duration_cast<microseconds>( t2 - t1 ).count(); | |
std::cout << "for_each " << duration << std::endl; | |
t1 = high_resolution_clock::now(); | |
auto sum3 = sum_accumulate(vec); | |
t2 = high_resolution_clock::now(); | |
duration = duration_cast<microseconds>( t2 - t1 ).count(); | |
std::cout << "accumulate " << duration << std::endl; | |
std::cout << sum1 << sum2 << sum3 <<std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment