im tryin to compare the time it takes to calculate squareroot by the stdlib function and recursive function. everythin's workin good except the TIME thing. its givein me the same time. wat is wrong??? plz help me find it.. thank you guys!

#include<iostream>
#include<iomanip>
#include<cmath>
#include<cstdlib>
#include<ctime>


using namespace std;


double sqroot(double,double,double);


void main()
{
int j,k,dif; double x,y,z; double a,b;
z=0.01; y=2;


cout<<"Enter the number you want to find the squareroot of : ";
cin>>x;


a=sqrt(x);
j=time(0);


b=sqroot(x,y,z);
k=time(0);


dif=k-j;


cout<<"By using the cstdlib the ans is           :"<<a<<endl;
cout<<"The time it took to calculate: "<<j<<endl;
cout<<"By using the recursive function the ans is :"<<b<<endl;
cout<<"The time it took to calculate: "<<k<<endl;
}


double sqroot(double num, double ans, double tol)
{


if (fabs((ans*ans)-num)<=tol)
return ans;
else
return sqroot(num,((ans*ans)+num)/(2*ans),tol);


}

Edited 3 Years Ago by happygeek: fixed formatting

Comments
Use code tags.

I've never seen the time function but I would just guess it would have to look like this.

a=sqrt(x);
j=time(sqrt(x));

Declare time variables like such

clock_t start, end;

start=clock();
end=clock();

cout<<"the total elapsed time is: "<<(end-start)/CLK_TCK<<"seconds"<<endl;

CLK_TCK is a predefined function in the time.h file, that translates clock ticks to seconds.

This "might" help ya

Comments
Helped me too

Jpowers22 is right, you need to use clock() to get to something that is about a millisecond. You also have to do the calculation about a million times to get a meaningful time to measure. Yes Ruby, computers are fast nowadays!

// time the sqrt() function    Dev-C++

#include <iostream>
#include <cmath>
#include <time.h>

using namespace std;

int main()
{
  int k;
  double a,x,y,z;
  clock_t start, end;
 
  z = 0.01; 
  y = 2;
  cout << "Enter the number you want to find the squareroot of : ";
  cin >> x;

  start = clock();
  for(k = 0; k < 1000000; k++)
    a = sqrt(x);
  end = clock();
  cout << "1M iterations of sqrt() from cmath took "; 
  cout << (end - start) << " ticks\n"; // a tick is about 1 ms 
 
  // now do a similar thing for sqroot(x,y,z)

  system("PAUSE");	
  return 0;
}
Comments
helped me too-- Asif_NSU
This article has been dead for over six months. Start a new discussion instead.