1 /*
2 * Copyright (C) 2021 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 "time_monitor.h"
16 #include <cinttypes>
17 #include "media_log.h"
18
19 namespace {
20 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "TimeMonitor"};
21 }
22
23 namespace OHOS {
24 namespace Media {
TimeMonitor(const std::string & objectName)25 TimeMonitor::TimeMonitor(const std::string &objectName)
26 : objectName_(objectName)
27 {
28 MEDIA_LOGD("0x%{public}06" PRIXPTR " Instances create", FAKE_POINTER(this));
29 }
30
~TimeMonitor()31 TimeMonitor::~TimeMonitor()
32 {
33 MEDIA_LOGD("0x%{public}06" PRIXPTR " Instances destroy", FAKE_POINTER(this));
34 }
35
StartTime()36 void TimeMonitor::StartTime()
37 {
38 int ret = gettimeofday(&startTime_, nullptr);
39 if (ret == -1) {
40 MEDIA_LOGE("get current time failed!");
41 }
42 isStart_ = true;
43 }
44
FinishTime()45 void TimeMonitor::FinishTime()
46 {
47 if (!isStart_) {
48 return;
49 }
50 int ret = gettimeofday(&finishTime_, nullptr);
51 if (ret == -1) {
52 MEDIA_LOGE("get current time failed!");
53 }
54 MEDIA_LOGD("%{public}s: elapsed time = %{public}" PRId64 " ms", objectName_.c_str(),
55 (Timeval2Sec(finishTime_, TIME_VAL_MS) - Timeval2Sec(startTime_, TIME_VAL_MS)));
56 isStart_ = false;
57 }
58
Timeval2Sec(const timeval & tv,TimeValType valType) const59 int64_t TimeMonitor::Timeval2Sec(const timeval &tv, TimeValType valType) const
60 {
61 if ((valType == TIME_VAL_MS) || (valType == TIME_VAL_US) || (valType == TIME_VAL_NS)) {
62 if ((static_cast<int64_t>(tv.tv_sec) < (LLONG_MAX / valType)) &&
63 (static_cast<int64_t>(tv.tv_usec) <= TIME_VAL_US)) {
64 return static_cast<int64_t>(tv.tv_sec) * valType + static_cast<int64_t>(tv.tv_usec) * valType / TIME_VAL_US;
65 } else {
66 MEDIA_LOGW("time overflow");
67 }
68 }
69 return -1;
70 }
71 } // namespace Media
72 } // namespace OHOS
73