simple_profile.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <stdio.h>
  2. #include <cds/simple_profile.h>
  3. #include <signal.h>
  4. #include <sys/time.h>
  5. #include <string.h>
  6. /* FIXME: only for testing */
  7. /*#include "dprint.h"*/
  8. #define trace_signal SIGTRAP
  9. typedef void (*_sig_t) (int);
  10. unsigned int tick_counter = 0;
  11. static struct sigaction old_sigprof_action;
  12. static _sig_t old_sigx_action;
  13. static int initialized = 0;
  14. static trace_f trace_function = NULL;
  15. int reset_timer()
  16. {
  17. struct itimerval tv;
  18. int res;
  19. tv.it_interval.tv_sec = 0;
  20. tv.it_interval.tv_usec = 1000;
  21. /*tv.it_interval.tv_usec = 10 * 1000; */
  22. tv.it_value.tv_sec = tv.it_interval.tv_sec;
  23. tv.it_value.tv_usec = tv.it_interval.tv_usec;
  24. res = setitimer(ITIMER_PROF, &tv, NULL);
  25. return res;
  26. }
  27. void prof_handler(int a, siginfo_t *info, void *b)
  28. {
  29. tick_counter++;
  30. /* LOG(L_ERR, "PROFILE HANDLER called\n"); */
  31. /* reset_timer(); */
  32. }
  33. void trace_handler(int a)
  34. {
  35. if (trace_function) trace_function();
  36. }
  37. int start_profile(trace_f tf)
  38. {
  39. struct sigaction action;
  40. int res;
  41. if (initialized) return 1;
  42. initialized = 1;
  43. trace_function = tf;
  44. memset(&action, 0, sizeof(action));
  45. action.sa_sigaction = prof_handler;
  46. sigemptyset(&action.sa_mask);
  47. action.sa_flags = SA_SIGINFO;
  48. res = sigaction(SIGPROF, &action, &old_sigprof_action);
  49. if (res != 0) {
  50. /* ERROR_LOG("can't set signal handle (%d)\n", res);*/
  51. return -1;
  52. }
  53. old_sigx_action = signal(trace_signal, &trace_handler);
  54. res = reset_timer();
  55. if (res != 0) {
  56. /* ERROR_LOG("can't set itimer (%d)\n", res);*/
  57. signal(trace_signal, old_sigx_action);
  58. sigaction(SIGPROF, &old_sigprof_action, NULL);
  59. return -1;
  60. }
  61. return 0;
  62. }
  63. int stop_profile()
  64. {
  65. if (initialized) {
  66. initialized = 0;
  67. signal(trace_signal, old_sigx_action);
  68. return sigaction(SIGPROF, &old_sigprof_action, NULL);
  69. }
  70. else return -1;
  71. }