Last active
April 11, 2016 22:39
-
-
Save alexhsamuel/cf413472ebdef702a50e67bcc89109bc to your computer and use it in GitHub Desktop.
using std::chrono to time a function, fully inlined
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
#include <chrono> | |
#include <utility> | |
//------------------------------------------------------------------------------ | |
using Elapsed = double; | |
template<typename FN, typename ...ARGS> | |
inline std::pair<Elapsed, std::result_of_t<FN&&(ARGS&&...)>> | |
time1( | |
FN&& fn, | |
ARGS&&... args) | |
{ | |
auto const start = std::chrono::high_resolution_clock::now(); | |
auto const result = fn(std::forward<ARGS>(args)...); | |
auto const end = std::chrono::high_resolution_clock::now(); | |
return {std::chrono::duration<Elapsed>(end - start).count(), result}; | |
} | |
//------------------------------------------------------------------------------ | |
template<typename T> | |
T | |
dot( | |
size_t const num, | |
T const* const arg0, | |
T const* const arg1) | |
{ | |
T result = 0; | |
for (size_t i = 0; i < num; ++i) | |
result += arg0[i] * arg1[i]; | |
return result; | |
} | |
//------------------------------------------------------------------------------ | |
#include <iostream> | |
#include <unistd.h> | |
int | |
main() | |
{ | |
size_t const num = 1024 * 1024; | |
double* const arr0 = new double[num]; | |
double* const arr1 = new double[num]; | |
for (size_t i = 0; i < num; ++i) { | |
arr0[i] = i + 1; | |
arr1[i] = 1.0 / (i + 1); | |
} | |
auto const result = time1(dot<double>, num, arr0, arr1); | |
std::cout << "result=" << result.second << "\n" | |
<< "timing=" << result.first << std::endl; | |
return EXIT_SUCCESS; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment