usleep () para calcular o tempo decorrido se comporta estranho
Estou calculando o tempo decorrido em mili segundos para cada chamada sucessiva à função de manipulador usando o código abaixo. Quando eu uso usleep (1000), ou seja, a diferença de tempo de 1 ms entre cada chamada é de 10 ms e quando eu uso usleep (1000000), ou seja, 1 seg surpreendentemente intervalo de tempo entre cada chamada cai para menos de 1 ms. A seguir está o trecho de código:
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<unistd.h>
struct timeval start_time;
void handler(int);
int main()
{
struct timeval current_time;
int i=0;
gettimeofday(&start_time,0);
gettimeofday(¤t_time,0);
printf("%012.3fms: emulationbegins\n",((current_time.tv_usec-start_time.tv_usec)/1000.0));
while(i++<5)
{
usleep(1000); // compare with usleep(1000000)
handler(i);
}
return 0;
}
void handler(int i)
{
printf("In Handler %d\n",i);
struct timeval current_time;
gettimeofday(¤t_time,0);
printf("%012.3fms: Handler Called\n",((current_time.tv_usec-start_time.tv_usec)/1000.0));
return;
}