utils.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/time.h>
  4. #include <malloc.h>
  5. #include <sched.h>
  6. #include "utils.h"
  7. /**
  8. * Calculate a duration
  9. *
  10. * @param start start of the computing or null if
  11. * this is the first time this function is inoked
  12. *
  13. * @return current time
  14. */
  15. struct timeval* showTime(struct timeval* start)
  16. {
  17. struct timeval* stop;
  18. long tv_sec;
  19. long tv_usec;
  20. stop = (struct timeval*)malloc(sizeof(struct timeval));
  21. gettimeofday(stop, 0);
  22. if (!start) return stop;
  23. tv_sec = (start->tv_usec > stop->tv_usec) ? stop->tv_sec - start->tv_sec - 1 : stop->tv_sec - start->tv_sec;
  24. tv_usec = (start->tv_usec > stop->tv_usec) ? 1000000 + stop->tv_usec - start->tv_usec : stop->tv_usec - start->tv_usec;
  25. fprintf(stderr, "%lus %lums %luµs\n", tv_sec, tv_usec/1000, tv_sec % 1000);
  26. return stop;
  27. }
  28. /**
  29. * Switch between standard and real-time mode
  30. *
  31. * @param mode (REAL_TIME | STANDARD)
  32. */
  33. void cpuMode(int mode)
  34. {
  35. struct sched_param p;
  36. switch (mode) {
  37. case REAL_TIME:
  38. p.__sched_priority = sched_get_priority_max(SCHED_RR);
  39. if( sched_setscheduler( 0, SCHED_RR, &p ) == -1 ) {
  40. perror("Failed to switch to realtime scheduler.");
  41. }
  42. break;
  43. case STANDARD:
  44. default:
  45. p.__sched_priority = 0;
  46. if( sched_setscheduler( 0, SCHED_OTHER, &p ) == -1 ) {
  47. perror("Failed to switch to normal scheduler.");
  48. }
  49. break;
  50. }
  51. }