How would I get the code below to time both the iterative version and the recursive
version of the Fibonacci function so that I can see which one is faster. I already have the timer.h file to go along with it. I'm thinking i should use t.start() and t.stop() to time it. help please? thank you!

#include <iostream>
using namespace std;
#include "timer.h"

unsigned iterFibonacci(unsigned n);

unsigned recFibonacci(unsigned n);
int main()
Timer t;
unsigned x;

cout << "Please enter a positive integer: ";
cin >> x;

// Now print the result of the iterative version of the function
cout << "Iterative fib(" << x << ") = " << iterFibonacci(x) << endl;

// Now print the result of the recursive version of the function
// cout << "Recursive fib(" << x << ") = " << recFibonacci(x) << endl;

//--- Definition of iterFibonacci()
unsigned iterFibonacci(unsigned n)
nextFib = 1, // the next Fibonacci number to be calculated
previousFib = 1, // the Fibonacci number before it
beforePreviousFib; // the Fibonacci number before that one

for (int i = 3; i <= n; i++)
// First, update the previous and before previous values
beforePreviousFib = previousFib;
previousFib = nextFib;

// Then compute the next Fibonacci value
nextFib = previousFib + beforePreviousFib;

return nextFib;

//--- Definition of recFibonacci()
unsigned recFibonacci(unsigned n)

// Add statements for RecFibonacci() here
6 Years
Discussion Span
Last Post by Software guy

Hope this helps if you dont understand anything let me know

#include <stdio.h>
#include <time.h>

int main ()
  time_t start,end;
  double diff;

  int i; 
  time (&start);


  time (&end);
  diff = difftime (end,start);

   printf("\nTime Taken: %d",diff);
  return 0;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.