2
  struct timeval start, end;
  start.tv_usec = 0;
  end.tv_usec = 0;

  gettimeofday(&start, NULL);

  functionA();

  gettimeofday(&end, NULL);

  long t = end.tv_usec - start.tv_usec;
  printf("Total elapsed time %ld us \n", t);

I am calculating the total elapsed time like this but it sometimes shows a negative value. What might be cause the problem?

Thanks in advance.

codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167
  • A related disscusion (including a solution) could be found here: http://stackoverflow.com/questions/7675136/how-to-calculate-the-execution-time-in-c/7675302#7675302 – alk Oct 17 '11 at 20:14

3 Answers3

4

Keep in mind that there is both a seconds and micro-seconds field of that structure. Therefore if you are simply subtracting the micro-seconds field, you could have a time that is later in seconds, but the microseconds field is less. For instance, and end-time of 5 seconds, 100 microseconds will have a negative result compared to 4 seconds and 5000 microseconds with the subtraction method you're using. In order to get the proper result, you have to take into account both the seconds and micro-seconds fields of the structure. This can be done doing the following:

long seconds = end.tv_sec - start.tv_sec;
long micro_seconds = end.tv_usec - start.tv_usec;

if (micro_seconds < 0)
{
    seconds -= 1;
}

long total_micro_seconds = (seconds * 1000000) + abs(micro_seconds);
Jason
  • 31,834
  • 7
  • 59
  • 78
3

maybe something along the lines of:

long t = (end.tv_sec*1e6 + end.tv_usec) - (start.tv_sec*1e6 + start.tv_usec);

Vinicius Kamakura
  • 7,665
  • 1
  • 29
  • 43
0

From The GNU C Library:

Data Type: struct timeval

The struct timeval structure represents an elapsed time. It is declared in sys/time.h and has the following members:

long int tv_sec

This represents the number of whole seconds of elapsed time.

long int tv_usec

This is the rest of the elapsed time (a fraction of a second), represented as the number of microseconds. It is always less than one million.

The only thing you're subtracting is the microseconds in tv_usec above the full seconds value in tv_sec. You need to work with both values in order to find the exact microsecond difference between the two times.

Adam Maras
  • 26,269
  • 6
  • 65
  • 91