0

This results in microseconds being displayed how would I get it to display in milliseconds? current output is 34.0000?????

double time_diff(struct timeval x , struct timeval y);

int main()
{  
int i;

struct timeval before , after;
gettimeofday(&before , NULL);

//Time taking task
for (i=1 ; i <= 100 ; i++)
{
    printf("%d %d %d n",i, i*i, i*i*i);
}

gettimeofday(&after , NULL);

printf(" time elapsed : %.0lf" , time_diff(before , after) ); 

return 0;
 }

double time_diff(struct timeval x , struct timeval y)
{
    double x_ms , y_ms , diff;

x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;

diff = (double)y_ms - (double)x_ms;

return diff;
 }

Would I just want to multiply by only 1000???

1
  • I think you need to rephrase your question to make it easier to understand. What exact result are you after? Feb 24, 2016 at 23:30

2 Answers 2

1

Why you try to use some construction not designed to measure time in seconds or ms. Try this:

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

double time_diff(double x , double y);

int main()
{  
   int i;

   double before;
   before = clock();

   //Time taking task
   for (i=1 ; i <= 100 ; i++)
   {
       printf("%d %d %d n",i, i*i, i*i*i);
   }

    printf("\n\ntime elapsed : %.8lf", time_diff(before, clock())); 

   return 0;
 }


double time_diff(double x , double y)
{
    return ((y - x)/CLOCKS_PER_SEC) * 100;
}
1

Divide the result by 1000 to get in milliseconds.

2
  • so just do diff= diff/1000 then return diff?
    – aaaa
    Feb 24, 2016 at 20:59
  • Yes... but not sure why you want to convert to milli seconds?
    – cosmos
    Feb 24, 2016 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.