Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <chrono>
- using namespace std;
- using namespace std::chrono;
- typedef unsigned long long ull;
- //Simplest timer i can implement
- class Timer {
- public:
- Timer() : start{ clock_t::now() } {}
- void restart() {
- start = clock_t::now();
- }
- double get_elapsed() const {
- auto micro_elapsed = duration_cast<microseconds>(clock_t::now() - start).count();
- return micro_elapsed / 1e3;
- }
- private:
- using clock_t = high_resolution_clock;
- time_point<clock_t> start;
- };
- ull calls_fib = 0, calls_fib_dp = 0;
- vector<ull> fib_dp_res;
- ull fib(ull pos) {
- //we are counting the number of function calls
- calls_fib += 1;
- // Fibonacci sequence starts with 0, then 1:
- // Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21...
- if (pos == 0) return 0;
- if (pos == 1) return 1;
- return fib(pos - 1) + fib(pos - 2);
- }
- ull fib_dp(ull pos) {
- //we are counting the number of function calls
- calls_fib_dp += 1;
- if (pos < fib_dp_res.size())
- return fib_dp_res[pos];
- // Fibonacci sequence starts with 0, then 1:
- // Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21...
- if (pos == 0) {
- fib_dp_res.push_back(0);
- return fib_dp_res[pos];
- }
- fib_dp(pos - 1);
- if (pos == 1 and fib_dp_res.size() == 1) {
- fib_dp_res.push_back(1);
- return fib_dp_res[pos];
- }
- fib_dp_res.push_back(fib_dp_res[pos - 1] + fib_dp_res[pos - 2]);
- return fib_dp_res[pos];
- }
- int main() {
- ull position = 40;
- ull fib_res, fib_dp_res;
- Timer fib_res_timer;
- fib_res = fib(position);
- auto fib_res_time = fib_res_timer.get_elapsed();
- Timer fib_dp_res_timer;
- fib_dp_res = fib_dp(position);
- auto fib_dp_res_time = fib_dp_res_timer.get_elapsed();
- cout << "fib(" << position << ") was called. Result is " << fib_res
- << ". fib() was called " << calls_fib << " times." << " Elapsed time is: " << fib_res_time << " ms" << endl;
- cout << "fib_dp(" << position << ") was called. Result is " << fib_dp_res
- << ". fib_dp() was called " << calls_fib_dp << " times." << " Elapsed time is: " << fib_dp_res_time << " ms" << endl;
- }
Add Comment
Please, Sign In to add comment