In78
In78

Reputation: 462

Calculating the time taken by a program

Use the series tan{-­1}(x) = x – x3 / 3 + x5 / 5 – x7 / 7 + ... to calculate the value of pi. How fast is the convergence? My attempt:

/* Calculating the value of pi */

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

// To calculate tan inverse
float CalculateInverseTan(float fX)
{
    float fY = 0;
    float fSign = 1;
    float fTerm = 0;
    int iii = 1;
    do
    {
        float fPow = 1;
        int jjj;
        // Calculating the power
        for (jjj = 1; jjj <= iii; jjj++)
        {
            fPow *= fX;
        }
        fTerm = fSign * (fPow / iii);
        fY += fTerm;
        iii += 2;
        fSign *= -1;
    } while (fTerm > 0.0001 || fTerm < -0.0001);
    return fY;
}

int main()
{
    printf("Let x = tan^(-1)(1).\n");
    time_t start = time(0);
    float fTanInverse1 = CalculateInverseTan(1);
    time_t end = time(0);
    printf("Therefore x = %f. Time of convergence = %f sec.\nAs x  = pi/4, therefore pi = 4x.\nTherefore pi = %f\n", fTanInverse1, difftime(start, end), 4 * fTanInverse1);
    return 0;
}

I have managed to calculate the value of pi. But the time of convergence is always coming as 0.

Upvotes: 1

Views: 2029

Answers (3)

ANjaNA
ANjaNA

Reputation: 1426

Use this method.

#include <time.h>

int main() {
clock_t start, end;
double cpu_time_used;

start = clock();


… /* Do the work. */


end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
return 0;
}

Upvotes: 2

Milinda Kasun
Milinda Kasun

Reputation: 75

Use the cpu time To get a process CPU time, you can also use the clock function. This is also declared in the header file `time.h'. you can use a code like this,

`double cpu_time;

clock_t start = clock();

/* your function */

clock_t end = clock();

cpu_time = ((double) (end - start)) / CLOCKS_PER_SEC;`

Upvotes: 0

Loocid
Loocid

Reputation: 6451

Does it look like your program completes in < 1 second?

If that is the case, you will get a result of 0 because the time function has a resolution of only 1 second.

You could instead use the clock function which measures time in terms of ticks of your CPU, then you can convert it back to seconds.

See here for usage and more information.

Upvotes: 3

Related Questions