How to subtract two gettimeofday instances?

user1106106 picture user1106106 · Dec 29, 2011 · Viewed 7.7k times · Source

I want to subtract two gettimeofday instances, and present the answer in milliseconds.

The idea is:

  static struct timeval tv;
  gettimeofday(&tv, NULL);

  static struct timeval tv2;
  gettimeofday(&tv2, NULL);

  static struct timeval tv3=tv2-tv;

and then convert 'tv3' into milliseconds resolution.

Answer

janneb picture janneb · Dec 29, 2011

You can use the timersub() function provided by glibc, then convert the result to milliseconds (watch out for overflows when doing this, though!).