struct TimePrinter {
timeval t1, t2;
std::string name;
TimePrinter(const std::string &name_) : name(name_) {
gettimeofday(&t1, NULL);
}
~TimePrinter() {
gettimeofday(&t2, NULL);
double elapsedTime;
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
std::cerr << name << " tooks " << elapsedTime << " ms" << std::endl;
}
};
std::vector<double> v1(10000000), v2(10000000), v3;
{
TimePrinter printer("sum");
sum(v3, v1, v2);
}
{
TimePrinter printer("direct sum");
direct_sum(v3, v1, v2);
}
{
TimePrinter printer("transform sum");
direct_sum_transform(v3, v1, v2);
}
template <class T>
inline void direct_sum_transform(std::vector<T> &result, const std::vector<T> &a,
const std::vector<T> &b) {
if (a.size() != b.size())
throw std::invalid_argument("vectors must have same size");
if (result.size() < a.size()) result.resize(a.size());
std::transform(std::begin(a), std::end(a), std::begin(b), std::begin(result),
std::plus<T>());
}