profile.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. * Dead simple processor sampling profiling code.
  3. *
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include "windows.h"
  8. static int *Profile_table = NULL;
  9. static int Profile_table_size = 0;
  10. static int Profile_table_granularity = 0;
  11. static DWORD (*ProfileFn)(void *);
  12. static void *ProfileArgs;
  13. static volatile HANDLE threadToProfile = NULL;
  14. static volatile HANDLE thread = NULL;
  15. static volatile int die = 0;
  16. static volatile int taskDone = 0;
  17. void Profile_dump()
  18. {
  19. FILE *file;
  20. die = 1;
  21. while (die)
  22. {
  23. Sleep(1);
  24. }
  25. file = fopen("profile", "wb");
  26. if(file == NULL)
  27. {
  28. Output("Failed to open profile output");
  29. return;
  30. }
  31. Output("Dumping profile...");
  32. fputc('P', file);
  33. fputc('R', file);
  34. fputc('0', file);
  35. fputc('F', file);
  36. fwrite(&Profile_table_granularity, 4, 1, file);
  37. fwrite(Profile_table, 4, Profile_table_size>>2, file);
  38. fclose(file);
  39. }
  40. static DWORD ticker(LPVOID dummy)
  41. {
  42. CONTEXT context;
  43. int offset;
  44. memset(&context, 0, sizeof(CONTEXT));
  45. {
  46. while (!die)
  47. {
  48. Sleep(10);
  49. context.ContextFlags = CONTEXT_FULL;
  50. if (GetThreadContext(thread, &context))
  51. {
  52. offset = context.Pc & ~0xF0000000;
  53. offset >>= Profile_table_granularity+2;
  54. if (offset >= (Profile_table_size>>2))
  55. {
  56. offset = 0;
  57. }
  58. }
  59. else
  60. {
  61. offset = 0;
  62. }
  63. Profile_table[offset]++;
  64. }
  65. }
  66. die = 0;
  67. }
  68. void Profile_init(int size,
  69. int granularity)
  70. {
  71. HANDLE myThread;
  72. Profile_table_granularity = granularity;
  73. Profile_table_size = (size+(1<<granularity)-1)>>granularity;
  74. Profile_table = (int *)malloc(Profile_table_size);
  75. if (Profile_table == NULL)
  76. {
  77. Output("Failed to get memory for Profile table\n");
  78. exit(EXIT_FAILURE);
  79. }
  80. memset(Profile_table, 0, Profile_table_size);
  81. thread = (HANDLE)GetCurrentThreadId();
  82. Output("Commencing profiling");
  83. myThread = CreateThread(NULL, /* Security Attributes */
  84. 0,
  85. &ticker,
  86. NULL,
  87. 0,
  88. NULL);
  89. if (myThread == NULL)
  90. {
  91. Output("Profiler failed to start");
  92. exit(EXIT_FAILURE);
  93. }
  94. SetThreadPriority(myThread, THREAD_PRIORITY_ABOVE_NORMAL);
  95. }