fork(73) download
  1. #include <iostream>
  2. #include <chrono>
  3.  
  4.  
  5. template<typename TimeT = std::chrono::milliseconds>
  6. struct measure
  7. {
  8. template<typename F, typename ...Args>
  9. static typename TimeT::rep execution(F func, Args&&... args)
  10. {
  11. auto start = std::chrono::system_clock::now();
  12.  
  13. // Now call the function with all the parameters you need.
  14. func(std::forward<Args>(args)...);
  15.  
  16. auto duration = std::chrono::duration_cast< TimeT>
  17. (std::chrono::system_clock::now() - start);
  18.  
  19. return duration.count();
  20. }
  21. };
  22.  
  23. struct functor
  24. {
  25. int state;
  26. functor(int state) : state(state) {}
  27. void operator()() const
  28. {
  29. std::cout << "In functor run for ";
  30. }
  31. };
  32.  
  33. void func()
  34. {
  35. std::cout << "In function, run for ";
  36. }
  37.  
  38.  
  39. int main()
  40. {
  41. int dummy(3);
  42.  
  43. std::cout << measure<std::chrono::nanoseconds>::execution( [&dummy]()
  44. {
  45. dummy *= 2; // usage with lambdas
  46. std::cout << "In lambda, run for ";
  47. }) << std::endl;
  48.  
  49. std::cout << measure<std::chrono::nanoseconds>::execution(functor(dummy)) << std::endl;
  50.  
  51. std::cout << measure<std::chrono::nanoseconds>::execution(func);
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
In lambda, run for 18918
In functor run for 804
In function, run for 1718