elapsed_timer.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_TIMER_ELAPSED_TIMER_H_
  5. #define BASE_TIMER_ELAPSED_TIMER_H_
  6. #include "base/base_export.h"
  7. #include "base/macros.h"
  8. #include "base/time/time.h"
  9. namespace base {
  10. // A simple wrapper around TimeTicks::Now().
  11. class BASE_EXPORT ElapsedTimer {
  12. public:
  13. ElapsedTimer();
  14. ElapsedTimer(ElapsedTimer&& other);
  15. void operator=(ElapsedTimer&& other);
  16. // Returns the time elapsed since object construction.
  17. TimeDelta Elapsed() const;
  18. // Returns the timestamp of the creation of this timer.
  19. TimeTicks Begin() const { return begin_; }
  20. private:
  21. TimeTicks begin_;
  22. DISALLOW_COPY_AND_ASSIGN(ElapsedTimer);
  23. };
  24. // A simple wrapper around ThreadTicks::Now().
  25. class BASE_EXPORT ElapsedThreadTimer {
  26. public:
  27. ElapsedThreadTimer();
  28. // Returns the ThreadTicks time elapsed since object construction.
  29. // Only valid if |is_supported()| returns true, otherwise returns TimeDelta().
  30. TimeDelta Elapsed() const;
  31. bool is_supported() const { return is_supported_; }
  32. private:
  33. const bool is_supported_;
  34. const ThreadTicks begin_;
  35. DISALLOW_COPY_AND_ASSIGN(ElapsedThreadTimer);
  36. };
  37. // Whenever there's a ScopedMockElapsedTimersForTest in scope,
  38. // Elapsed(Thread)Timers will always return kMockElapsedTime from Elapsed().
  39. // This is useful, for example, in unit tests that verify that their impl
  40. // records timing histograms. It enables such tests to observe reliable timings.
  41. class BASE_EXPORT ScopedMockElapsedTimersForTest {
  42. public:
  43. static constexpr TimeDelta kMockElapsedTime =
  44. TimeDelta::FromMilliseconds(1337);
  45. // ScopedMockElapsedTimersForTest is not thread-safe (it must be instantiated
  46. // in a test before other threads begin using ElapsedTimers; and it must
  47. // conversely outlive any usage of ElapsedTimer in that test).
  48. ScopedMockElapsedTimersForTest();
  49. ~ScopedMockElapsedTimersForTest();
  50. private:
  51. DISALLOW_COPY_AND_ASSIGN(ScopedMockElapsedTimersForTest);
  52. };
  53. } // namespace base
  54. #endif // BASE_TIMER_ELAPSED_TIMER_H_