Skip to content

Instantly share code, notes, and snippets.

@greenbagels
Created June 25, 2015 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greenbagels/04a5ef1f3af1af81fd96 to your computer and use it in GitHub Desktop.
Save greenbagels/04a5ef1f3af1af81fd96 to your computer and use it in GitHub Desktop.
#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