Created
September 6, 2016 09:17
-
-
Save GZShi/a19ce22fd81df23757b0cfd999530e22 to your computer and use it in GitHub Desktop.
c++11 practice
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_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