elapsed_timer.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/time/time.h"
  8. namespace base {
  9. // A simple wrapper around TimeTicks::Now().
  10. class BASE_EXPORT ElapsedTimer {
  11. public:
  12. ElapsedTimer();
  13. ElapsedTimer(const ElapsedTimer&) = delete;
  14. ElapsedTimer& operator=(const ElapsedTimer&) = delete;
  15. ElapsedTimer(ElapsedTimer&& other);
  16. void operator=(ElapsedTimer&& other);
  17. // Returns the time elapsed since object construction.
  18. TimeDelta Elapsed() const;
  19. // Returns the timestamp of the creation of this timer.
  20. TimeTicks Begin() const { return begin_; }
  21. private:
  22. TimeTicks begin_;
  23. };
  24. // A simple wrapper around ThreadTicks::Now().
  25. class BASE_EXPORT ElapsedThreadTimer {
  26. public:
  27. ElapsedThreadTimer();
  28. ElapsedThreadTimer(const ElapsedThreadTimer&) = delete;
  29. ElapsedThreadTimer& operator=(const ElapsedThreadTimer&) = delete;
  30. // Returns the ThreadTicks time elapsed since object construction.
  31. // Only valid if |is_supported()| returns true, otherwise returns TimeDelta().
  32. TimeDelta Elapsed() const;
  33. bool is_supported() const { return is_supported_; }
  34. private:
  35. const bool is_supported_;
  36. const ThreadTicks begin_;
  37. };
  38. // Whenever there's a ScopedMockElapsedTimersForTest in scope,
  39. // Elapsed(Thread)Timers will always return kMockElapsedTime from Elapsed().
  40. // This is useful, for example, in unit tests that verify that their impl
  41. // records timing histograms. It enables such tests to observe reliable timings.
  42. class BASE_EXPORT ScopedMockElapsedTimersForTest {
  43. public:
  44. static constexpr TimeDelta kMockElapsedTime = Milliseconds(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(const ScopedMockElapsedTimersForTest&) =
  50. delete;
  51. ScopedMockElapsedTimersForTest& operator=(
  52. const ScopedMockElapsedTimersForTest&) = delete;
  53. ~ScopedMockElapsedTimersForTest();
  54. };
  55. } // namespace base
  56. #endif // BASE_TIMER_ELAPSED_TIMER_H_