/timer_nrp.c

https://bitbucket.org/tbindi/bubble-sort-vs-quick-sort · C · 57 lines · 42 code · 9 blank · 6 comment · 1 complexity · 24852bfb3586a99140a5a374ec8e28e5 MD5 · raw file

  1. // Tweaked from James Rochkind's description in the book
  2. // "Advanced unix programming".
  3. #include <sys/times.h>
  4. #include <unistd.h>
  5. #include <stdio.h>
  6. //#define DEBUG
  7. //#define SELF_TEST
  8. static struct tms tbuf1;
  9. static clock_t real1;
  10. static long clock_ticks;
  11. void timeStart(void)
  12. {
  13. real1 = times(&tbuf1);
  14. clock_ticks = sysconf(_SC_CLK_TCK);
  15. return;
  16. }
  17. double timeStop(char *msg)
  18. {
  19. struct tms tbuf2;
  20. clock_t real2;
  21. real2 = times(&tbuf2);
  22. double user = ((double)(tbuf2.tms_utime ) - (tbuf1.tms_utime )) / clock_ticks;
  23. double system = ((double)(tbuf2.tms_stime ) - (tbuf1.tms_stime )) / clock_ticks;
  24. #ifdef DEBUG
  25. double real = (double)(real2 - real1) / clock_ticks;
  26. #endif
  27. double userPlusSys = user+system;
  28. #ifdef DEBUG
  29. // This printing is just for self verification.
  30. printf("%s : Total %.2f (user/sys/real), %.2f , %.2f , %.2f \n", msg,userPlusSys, user, system, real);
  31. #endif
  32. return userPlusSys;
  33. }
  34. #ifdef SELF_TEST
  35. #define REPS 100000000
  36. main()
  37. {
  38. double dt;
  39. long unsigned i;
  40. timeStart();
  41. for (i=0; i<= REPS; i++)
  42. {
  43. (void)getpid();
  44. }
  45. dt = timeStop("pid");
  46. // do anything with dt
  47. }
  48. #endif