Skip to content

Instantly share code, notes, and snippets.

@irtaylor
Last active December 3, 2017 03:32
Show Gist options
  • Save irtaylor/bc4da60b941150e074a9fe4daba6cbde to your computer and use it in GitHub Desktop.
Save irtaylor/bc4da60b941150e074a9fe4daba6cbde to your computer and use it in GitHub Desktop.
a c++ performance test for dynamic programming fibonacci calculations vs naive recursive calculations
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <ctime>
using std::clock_t;
#include <map>
using std::map;
// segfaults when calculating 130954
int _dp_fib_helper(int n, map<int, int>* memo) {
if((*memo).count(n)) {
return (*memo)[n];
}
int f;
(n <= 2) ? f = 1 : f = _dp_fib_helper(n - 1, memo) + _dp_fib_helper(n - 2, memo);
(*memo)[n] = f;
return f;
}
int dp_fib(int n) {
map<int,int>* memo = new map<int,int>();
int f = _dp_fib_helper(n, memo);
delete(memo);
return f;
}
int fib(int n) {
if(n <= 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
int main() {
int n = 0;
int f = 0;
double elapsed_secs = 0;
/* NAIVE FIBONACCI */
cout << "Enter an int for regular fib:" << endl;
cin >> n;
clock_t begin = clock();
f = fib(n);
clock_t end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "FIB:\t" << f << "\tTIME:\t" << elapsed_secs << endl;
/* DP FIBONACCI */
cout << "\nEnter an int for dynamic programming fib:" << endl;
cin >> n;
begin = clock();
f = dp_fib(n);
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << "FIB:\t" << f << "\tTIME:\t" << elapsed_secs << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment