sleep_us.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/time.h>
  4. #include <stddef.h>
  5. #include <unistd.h>
  6. #include <time.h>
  7. /* From Advanced Programming in the Unix Environment
  8. * by W. Richard Stevens. */
  9. /* Sleep for a number of microseconds */
  10. void sleep_us1(unsigned int nusecs) {
  11. usleep(nusecs);
  12. }
  13. void sleep_us(unsigned int nusecs) {
  14. struct timeval tval;
  15. /* If we don't need to sleep then leave */
  16. if (nusecs < 1) {
  17. return;
  18. }
  19. tval.tv_sec = nusecs / 1000000L;
  20. tval.tv_usec = nusecs % 1000000L;
  21. select(0,NULL, NULL, NULL, &tval);
  22. }
  23. void sleep_us_loop(unsigned int nusecs) {
  24. volatile int i;
  25. for (i = 0; i < nusecs*200; i++) {
  26. }
  27. }
  28. void sleep_us_ns(unsigned int nusecs) {
  29. struct timespec tval;
  30. /* Input is number of microseconds.
  31. * 1 second = 1000000 microseconds.
  32. * 1 second = 1000000000 nanoseconds
  33. */
  34. tval.tv_sec = nusecs / 1000000L;
  35. /* Note that nsec = microseconds */
  36. tval.tv_nsec = nusecs % 1000000L;
  37. /* So we need to conert it to nanoseconds */
  38. tval.tv_nsec = tval.tv_nsec * 1000;
  39. nanosleep(&tval,&tval);
  40. }