2006年12月18日星期一

Use select as "sleep"

The function "select" can be used as a "timer", and it is more accurate than "sleep". And in most program, select but not sleep is used. Below is a example:

#include "sys/time.h"
#include "unistd.h"
#include "stdio.h"

int main(void)
{
  timeval tv;
  timeval tv0;
  timeval tv1;
  float timeuse;

  tv.tv_sec = 10;
  tv.tv_usec = 0;

  gettimeofday(&tv0, NULL);
  // Here select is same as "sleep(10)",
  // but more accurate than sleep

  select(0, NULL, NULL, NULL, &tv);
  gettimeofday(&tv1, NULL);

  timeuse = 1000000*(tv0.tv_sec - tv1.tv_sec) +
    tv0.tv_usec - tv1.tv_usec;
  timeuse /= 1000000;
  printf("The time used is %f\n", timeuse);
}

没有评论: