Last active
June 29, 2017 00:05
-
-
Save LesleyLai/a12a60ba38f69b4b606b33f55c5d0778 to your computer and use it in GitHub Desktop.
Benchmark for functions in C++
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
#ifndef BENCHMARK_HPP | |
#define BENCHMARK_HPP | |
/*! | |
* \file benchmark.hpp | |
* | |
* Benchmark for functions in C++. Use it only in release mode. | |
*/ | |
#include <iostream> | |
#include <functional> | |
#include <chrono> | |
#include <string> | |
/*! | |
* \brief Benchmarks the run speed of a function. | |
* \param message The message to print | |
* \param func The function to be evaluated. This function have zero arguments. | |
* \param compute_times Times to compute the function | |
* | |
* Runs the function func compute_times times and use the average time as result. | |
*/ | |
template <typename F> | |
void evaluate_speed(const std::string &message, | |
F func, | |
int compute_times = 100) { | |
auto start = std::chrono::high_resolution_clock::now(); | |
for (auto i = 0; i != compute_times; ++i) { | |
func(); | |
} | |
auto end = std::chrono::high_resolution_clock::now(); | |
auto total_time = std::chrono::duration_cast<std::chrono::milliseconds> | |
(end - start).count(); | |
auto average_time = static_cast<double>(total_time) / compute_times; | |
std::cout << message << ": " << average_time << "ms\n"; | |
} | |
#endif // BENCHMARK_HPP |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment