1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #include "timing.h" 16 17 #include <chrono> 18 #include <map> 19 20 static constexpr const double MICROSECONDS_TO_MILLISECONDS = 1000.0; 21 22 namespace OHOS::NetStack::Timing { RecieveTimer(const char * const type)23Timer &TimerMap::RecieveTimer(const char *const type) 24 { 25 std::map<const char *const, Timer>::iterator it = timerMap_.find(type); 26 if (it != timerMap_.end()) { 27 return it->second; 28 } else { 29 Timer timer; 30 timer.timerName_ = type; 31 timerMap_.insert(std::pair<const char *const, Timer>(type, timer)); 32 return timerMap_[type]; 33 } 34 } 35 Timer()36Timer::Timer() {} 37 Start()38void Timer::Start() 39 { 40 Timer::Start(0L); 41 } 42 Start(time_t time)43void Timer::Start(time_t time) 44 { 45 if (time > 0) { 46 startTime_ = time; 47 } else { 48 startTime_ = TimeUtils::GetNowTimeMicroseconds(); 49 } 50 } 51 Stop()52void Timer::Stop() 53 { 54 endTime_ = TimeUtils::GetNowTimeMicroseconds(); 55 } 56 Elapsed() const57double Timer::Elapsed() const 58 { 59 double elapsedTime = TimeUtils::Microseconds2Milliseconds(endTime_ - startTime_); 60 return elapsedTime <= 0 ? 0 : elapsedTime; 61 } 62 GetNowTimeMicroseconds()63time_t TimeUtils::GetNowTimeMicroseconds() 64 { 65 auto now = std::chrono::system_clock::now(); 66 return std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count(); 67 } 68 Microseconds2Milliseconds(time_t microseconds)69double TimeUtils::Microseconds2Milliseconds(time_t microseconds) 70 { 71 if (microseconds == 0) { 72 return 0.0; 73 } 74 return double(microseconds / MICROSECONDS_TO_MILLISECONDS); 75 } 76 } // namespace OHOS::NetStack::Timing