以下のコードを使用して、ハンドラー関数を連続して呼び出すたびに経過時間をミリ秒単位で計算しています。usleep(1000)を使用する場合、つまり各呼び出し間の1ミリ秒の時間差は10ミリ秒であり、usleep(1000000)を使用する場合、つまり1秒の場合、各呼び出し間の時間間隔は1ミリ秒未満になります。以下はコードスニペットです:
#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;
}