timer.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #ifndef TIMER_H
  2. #define TIMER_H
  3. #include "fixed_point.h"
  4. #include <sys/time.h>
  5. #include <vector>
  6. UInt64 rdtsc(void);
  7. class Timer
  8. {
  9. public:
  10. bool switched;
  11. Timer();
  12. ~Timer();
  13. /** Start timing */
  14. void start(void);
  15. /** Return elapsed time in nanoseconds */
  16. UInt64 getTime(void);
  17. static UInt64 now(void);
  18. private:
  19. UInt64 t_start;
  20. UInt64 r_start;
  21. UInt32 cpu_start;
  22. // Default FixedPoint uses a 16k multiplier, this overflows with long simulation times.
  23. // Now, we can simulate at least 3 months (0x100 * rdtsc() < INT64_MAX) with sufficient precision
  24. typedef TFixedPoint<0x100> RdtscSpeed;
  25. static RdtscSpeed rdtsc_speed;
  26. };
  27. class TotalTimer
  28. {
  29. public:
  30. TotalTimer(String _name, UInt32 _ignore = 0);
  31. ~TotalTimer();
  32. void add(UInt64 t, bool switched = false) {
  33. __sync_fetch_and_add(&total, t);
  34. __sync_fetch_and_add(&n, 1);
  35. if (t > max)
  36. max = t;
  37. if (switched)
  38. __sync_fetch_and_add(&n_switched, 1);
  39. }
  40. void report(FILE* fp);
  41. static void reports(void);
  42. static TotalTimer* getTimerByStacktrace(String name);
  43. private:
  44. String name;
  45. UInt64 total;
  46. UInt64 n;
  47. UInt64 max;
  48. UInt64 n_switched;
  49. static const unsigned long BACKTRACE_SIZE = 8;
  50. void * backtrace_buffer[BACKTRACE_SIZE];
  51. unsigned long backtrace_n, backtrace_ignore;
  52. };
  53. class ScopedTimer
  54. {
  55. private:
  56. TotalTimer &total;
  57. Timer timer;
  58. public:
  59. ScopedTimer(TotalTimer &_total)
  60. : total(_total)
  61. {
  62. }
  63. ~ScopedTimer()
  64. {
  65. UInt64 t = timer.getTime();
  66. total.add(t, timer.switched);
  67. }
  68. };
  69. #endif // TIMER_H