unwind_bench.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
  2. #include "config.h"
  3. #include "base/basictypes.h"
  4. #include "gperftools/stacktrace.h"
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <stdint.h>
  8. #include "sys/ucontext.h"
  9. #if HAVE_LIBUNWIND_H
  10. #include <libunwind.h>
  11. #endif
  12. #include "run_benchmark.h"
  13. extern "C" void getcontext_light(ucontext_t *ctx);
  14. #define MAX_FRAMES 1024
  15. static void *frames[MAX_FRAMES];
  16. enum measure_mode {
  17. MODE_NOOP,
  18. MODE_WITH_CONTEXT,
  19. MODE_WITHOUT_CONTEXT
  20. };
  21. static int ATTRIBUTE_NOINLINE measure_unwind(int maxlevel, int mode) {
  22. int n;
  23. if (mode == MODE_NOOP)
  24. return 0;
  25. if (mode == MODE_WITH_CONTEXT) {
  26. ucontext_t uc;
  27. getcontext_light(&uc);
  28. n = GetStackTraceWithContext(frames, MAX_FRAMES, 0, &uc);
  29. } else {
  30. n = GetStackTrace(frames, MAX_FRAMES, 0);
  31. }
  32. if (n < maxlevel) {
  33. fprintf(stderr, "Expected at least %d frames, got %d\n", maxlevel, n);
  34. abort();
  35. }
  36. return 0;
  37. }
  38. static int ATTRIBUTE_NOINLINE frame_forcer(int rv) {
  39. return rv;
  40. }
  41. static int ATTRIBUTE_NOINLINE f1(int level, int maxlevel, int mode) {
  42. if (level == maxlevel)
  43. return frame_forcer(measure_unwind(maxlevel, mode));
  44. return frame_forcer(f1(level + 1, maxlevel, mode));
  45. }
  46. static void bench_unwind_no_op(long iterations, uintptr_t param) {
  47. do {
  48. f1(0, param, MODE_NOOP);
  49. iterations -= param;
  50. } while (iterations > 0);
  51. }
  52. static void bench_unwind_context(long iterations, uintptr_t param) {
  53. do {
  54. f1(0, param, MODE_WITH_CONTEXT);
  55. iterations -= param;
  56. } while (iterations > 0);
  57. }
  58. static void bench_unwind_no_context(long iterations, uintptr_t param) {
  59. do {
  60. f1(0, param, MODE_WITHOUT_CONTEXT);
  61. iterations -= param;
  62. } while (iterations > 0);
  63. }
  64. int main(void) {
  65. report_benchmark("unwind_no_op", bench_unwind_no_op, 100);
  66. report_benchmark("unwind_context", bench_unwind_context, 100);
  67. report_benchmark("unwind_no_context", bench_unwind_no_context, 100);
  68. //// TODO: somehow this fails at linking step. Figure out why this is missing
  69. // #if HAVE_LIBUNWIND_H
  70. // unw_set_caching_policy(unw_local_addr_space, UNW_CACHE_PER_THREAD);
  71. // #endif
  72. return 0;
  73. }