fork(2) download
  1.  
  2. #include <type_traits>
  3. #include <iostream>
  4. #include <chrono>
  5. using namespace std;
  6.  
  7. template <class Fn, class... Args>
  8. auto timer(Fn fn, Args && ... args)
  9. -> typename std::enable_if<
  10. !std::is_same< decltype( fn( std::forward<Args>(args) ... )), void >::value,
  11. std::pair<double, decltype(fn(args...))> >::type
  12. {
  13. static_assert(!std::is_void<decltype(fn(args...))>::value,
  14. "Call timer_void if return type is void!");
  15. auto start = std::chrono::high_resolution_clock::now();
  16. auto ret = fn(args...);
  17. auto end = std::chrono::high_resolution_clock::now();
  18. std::chrono::duration<double> elapsed_seconds = end - start;
  19. return { elapsed_seconds.count(), ret };
  20. }
  21.  
  22. // If fn returns void, only the time is returned
  23. template <class Fn, class ... Args>
  24. auto timer(Fn fn, Args && ... args) -> typename std::enable_if<
  25. std::is_same< decltype( fn( std::forward<Args>(args) ... )), void >::value,
  26. double>::type
  27. {
  28. static_assert(std::is_void<decltype(fn(args...))>::value,
  29. "Call timer for non void return type");
  30. auto start = std::chrono::high_resolution_clock::now();
  31. fn(args...);
  32. auto end = std::chrono::high_resolution_clock::now();
  33. std::chrono::duration<double> elapsed_seconds = end - start;
  34. return elapsed_seconds.count();
  35. }
  36.  
  37.  
  38.  
  39. int main () {
  40. //This call is ambigous if the templates have the same name
  41. std::cout << timer([](double a, double b){return a*b;},1,2).first;
  42. }
  43.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
2.94e-07