ctimetimeval

Measuring time in C gives wrong result


I am trying to measure time in C in microseconds. I tried this code, but the value time_passed is a huge number, instead of 0 (or 1).

   struct timeval start;
   settimeofday(&start,NULL);
   struct timeval stop;
   settimeofday(&stop,NULL);
   unsigned long long int time_passed = 
       (stop.tv_sec-start.tv_sec)*1000000 + (stop.tv_usec - start.tv_usec);
   printf("time passed: %llu us\n",time_passed);

Solution

  • You are calling settimeofday() when you should be calling gettimeofday()!