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 17 #ifndef MINDSPORE_CCSRC_FL_SERVER_ITERATION_TIMER_H_ 18 #define MINDSPORE_CCSRC_FL_SERVER_ITERATION_TIMER_H_ 19 20 #include <chrono> 21 #include <atomic> 22 #include <thread> 23 #include <functional> 24 #include "fl/server/common.h" 25 26 namespace mindspore { 27 namespace fl { 28 namespace server { 29 // IterationTimer controls the time window for the purpose of eliminating trailing time of each iteration. 30 class IterationTimer { 31 public: IterationTimer()32 IterationTimer() : running_(false), end_time_(0) {} 33 ~IterationTimer() = default; 34 35 // Start timing. The timer will stop after parameter 'duration' milliseconds. 36 void Start(const std::chrono::milliseconds &duration); 37 38 // Caller could use this method to manually stop timing, otherwise the timer will keep timing until it expires. 39 void Stop(); 40 41 // Set the callback which will be called when the timer expires. 42 void SetTimeOutCallBack(const TimeOutCb &timeout_cb); 43 44 // Judge whether current timestamp is out of time window's range since the Start function is called. 45 bool IsTimeOut(const std::chrono::milliseconds ×tamp) const; 46 47 // Judge whether the timer is keeping timing. 48 bool IsRunning() const; 49 50 private: 51 // The running state for the timer. 52 std::atomic<bool> running_; 53 54 // The timestamp in millesecond at which the timer should stop timing. 55 std::chrono::milliseconds end_time_; 56 57 // The thread that keeps timing and call timeout_callback_ when the timer expires. 58 std::thread monitor_thread_; 59 TimeOutCb timeout_callback_; 60 }; 61 } // namespace server 62 } // namespace fl 63 } // namespace mindspore 64 #endif // MINDSPORE_CCSRC_FL_SERVER_ITERATION_TIMER_H_ 65