Skip to content

Instantly share code, notes, and snippets.

@GZShi
Created September 6, 2016 09:17
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 GZShi/a19ce22fd81df23757b0cfd999530e22 to your computer and use it in GitHub Desktop.
Save GZShi/a19ce22fd81df23757b0cfd999530e22 to your computer and use it in GitHub Desktop.
c++11 practice
#ifndef __BENCHMARK_HPP_BY_GZSHI__
#define __BENCHMARK_HPP_BY_GZSHI__
#include <functional>
#include <chrono>
template<typename TClock, typename TFn, typename ...TArgs>
TClock benchmark(TFn&& fn, TArgs&&... args) {
auto exec = std::bind(std::forward<TFn>(fn), std::forward<TArgs>(args)...);
auto begin = std::chrono::steady_clock::now();
exec();
auto end = std::chrono::steady_clock::now();
return std::chrono::duration_cast<TClock>(end - begin);
}
#endif
/* example
```cpp
#include "benchmark.hpp"
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
function<int64_t(int32_t)> fibonacci = [&](int32_t index) -> int64_t {
return index < 2 ? index : (fibonacci(index - 1) + fibonacci(index - 2));
}
auto ms = benchmark<chrono::milliseconds>([&]() {
for (auto i = 0; i < 35; ++i) {
cout << "fibonacci(" << i << ") = " << fibonacci(i) << endl;
}
});
cout << "total: " << ms << "ms" << endl;
auto ns = benchmark<chrono::nanoseconds>([]() {
int64_t sum = 0;
for (auto i = 0; i < 1000000; ++i) {
sum += i;
}
cout << "sum = " << sum << endl;
});
cout << "total: " << ns << "ns" << endl;
return 0;
}
```
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment