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!


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 : ";




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;
return sqroot(num,((ans*ans)+num)/(2*ans),tol);

Dave Sinkula commented: Use code tags. +0

Recommended Answers

All 4 Replies

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


Declare time variables like such

clock_t start, end;


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

commented: Helped me too +1

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)

  return 0;
commented: helped me too-- Asif_NSU +1

reputation point 1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.