fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <cmath>
  4. #include <chrono>
  5. #include <functional>
  6.  
  7. class TimedSection {
  8. public:
  9. TimedSection(std::string nameOfMeasurment) : nameOfMeasurment(nameOfMeasurment) {
  10. start = std::chrono::high_resolution_clock::now();
  11. }
  12.  
  13. ~TimedSection() {
  14. auto elapsedTime = std::chrono::high_resolution_clock::now() - start;
  15. std::cout << "Measurment taken(" << nameOfMeasurment << ") Elapsed time: " <<
  16. std::chrono::duration_cast<std::chrono::nanoseconds>(elapsedTime).count() << "ns" << std::endl;
  17. }
  18.  
  19. private:
  20. std::string nameOfMeasurment;
  21. std::chrono::time_point<std::chrono::high_resolution_clock> start;
  22. };
  23.  
  24. template<typename Arg, typename F>
  25. auto memoize(F&& f) {
  26. return [f](Arg arg) {
  27. static std::unordered_map<Arg, decltype(f(arg))> memoizedArgs;
  28. if(memoizedArgs.find(arg) == memoizedArgs.end()) {
  29. memoizedArgs[arg] = f(arg);
  30. }
  31.  
  32. return memoizedArgs[arg];
  33. };
  34. }
  35.  
  36. int main() {
  37. std::function<int(int)> fib = [&fib](int n) {return n < 2 ? 1 : fib(n-1) + fib(n-2);};
  38.  
  39.  
  40. auto memoizedFib = memoize<int>(fib);
  41.  
  42. {
  43. TimedSection("without memoization");
  44. for(auto i = 0; i < 100; i++) {
  45. fib(30);
  46. }
  47. }
  48.  
  49. {
  50. TimedSection("with memoization");
  51. for(auto i = 0; i < 100; i++) {
  52. memoizedFib(30);
  53. }
  54. }
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 2.47s 3276KB
stdin
Standard input is empty
stdout
Measurment taken(without memoization) Elapsed time: 602ns
Measurment taken(with memoization) Elapsed time: 272ns