#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>

#define LOOPS 10000000

double get_time_of_day()
{
struct timeval tv;

gettimeofday(&tv, NULL);

return ((double)tv.tv_sec) + ((double)tv.tv_usec)/1000000;
}

int main()
{
double cur_time, next_time;
double deviations = 0;
int backwards = 0;
int i;

printf("Running %d gettimeofday() loops:\n", LOOPS);

cur_time = get_time_of_day();

for (i=0; i < LOOPS; i++) {
next_time = get_time_of_day();
if (next_time < cur_time) {
backwards++;
deviations += fabs(next_time - cur_time);
}
cur_time = next_time;
}

printf("Going backwards count: %d\n", backwards);
if (backwards != 0) {
printf("Going backwards average deviation: %.7f\n", deviations/backwards);
}
}
