You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

iteration_timer.h 2.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Copyright 2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef MINDSPORE_CCSRC_PS_SERVER_ITERATION_TIMER_H_
  17. #define MINDSPORE_CCSRC_PS_SERVER_ITERATION_TIMER_H_
  18. #include <chrono>
  19. #include <atomic>
  20. #include <thread>
  21. #include <functional>
  22. #include "ps/server/common.h"
  23. namespace mindspore {
  24. namespace ps {
  25. namespace server {
  26. // IterationTimer controls the time window for the purpose of eliminating trailing time of each iteration.
  27. class IterationTimer {
  28. public:
  29. IterationTimer() : running_(false), end_time_(0) {}
  30. ~IterationTimer() = default;
  31. // Start timing. The timer will stop after parameter 'duration' milliseconds.
  32. void Start(const std::chrono::milliseconds &duration);
  33. // Caller could use this method to manually stop timing, otherwise the timer will keep timing until it expires.
  34. void Stop();
  35. // Set the callback which will be called when the timer expires.
  36. void SetTimeOutCallBack(const TimeOutCb &timeout_cb);
  37. // Judge whether current timestamp is out of time window's range since the Start function is called.
  38. bool IsTimeOut(const std::chrono::milliseconds &timestamp);
  39. // Judge whether the timer is keeping timing.
  40. bool IsRunning();
  41. private:
  42. // The running state for the timer.
  43. std::atomic<bool> running_;
  44. // The timestamp in millesecond at which the timer should stop timing.
  45. std::chrono::milliseconds end_time_;
  46. // The thread that keeps timing and call timeout_callback_ when the timer expires.
  47. std::thread monitor_thread_;
  48. TimeOutCb timeout_callback_;
  49. };
  50. } // namespace server
  51. } // namespace ps
  52. } // namespace mindspore
  53. #endif // MINDSPORE_CCSRC_PS_SERVER_ITERATION_TIMER_H_