Jack welch - 1 year ago 134

C Question

I am trying to measure elapsed time in Linux. My answer keeps returning zero which makes no sense to me. Below is the way i measure time in my program.

`#include <stdio.h>`

#include <stdlib.h>

#include <math.h>

#include <time.h>

main()

{

double p16 = 1, pi = 0, precision = 1000;

int k;

unsigned long micros = 0;

float millis = 0.0;

clock_t start, end;

start = clock();

// This section calculates pi

for(k = 0; k <= precision; k++)

{

pi += 1.0 / p16 * (4.0 / (8 * k + 1) - 2.0 / (8 * k + 4) - 1.0 / (8 * k + 5) - 1.0 / (8 * k + 6));

p16 *= 16;

}

end = clock();

micros = end - start;

millis = micros / 1000;

printf("%f\n", millis); //my time keeps being returned as 0

printf("this value of pi is : %f\n", pi);

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

To start with you need to use floating point arithmetics. Any integer value divided by a larger integer value will be zero, always.

And of course you should actually *do* something between getting the start and end times.

By the way, if you have access to `gettimeofday`

it's normally preferred over `clock`

as it has higher resolution. Or maybe `clock_gettime`

which has even higher resolution.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**