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 
16 #include "frameworks/bridge/js_frontend/engine/common/js_api_perf.h"
17 
18 #include "base/utils/time_util.h"
19 
20 namespace OHOS::Ace::Framework {
21 
InsertJsBeginLog(const std::string & functionName,int64_t timeStamp)22 void JsApiPerf::InsertJsBeginLog(const std::string& functionName, int64_t timeStamp)
23 {
24     TimeStamp stamp = {
25         .name = functionName,
26         .startTime = timeStamp != 0 ? timeStamp : GetMicroTickCount(),
27     };
28     startTimeData_.push(stamp);
29 }
30 
InsertJsEndLog(const std::string & functionName,int64_t timeStamp)31 void JsApiPerf::InsertJsEndLog(const std::string& functionName, int64_t timeStamp)
32 {
33     if (startTimeData_.empty()) {
34         return;
35     }
36     const std::string& itemName = startTimeData_.top().name;
37     if (itemName == functionName) {
38         int64_t now = timeStamp != 0 ? timeStamp : GetMicroTickCount();
39         int64_t diff = now - startTimeData_.top().startTime;
40         InsertPerfLog(functionName, diff);
41         startTimeData_.pop();
42     }
43 }
44 
InsertPerfLog(const std::string & functionName,int64_t timeConsumed)45 void JsApiPerf::InsertPerfLog(const std::string& functionName, int64_t timeConsumed)
46 {
47     data_[functionName].emplace_back(timeConsumed);
48 }
49 
PrintToLogs() const50 std::string JsApiPerf::PrintToLogs() const
51 {
52     std::string result;
53     for (const auto& item : data_) {
54         int64_t sum = 0;
55         result.append(item.first);
56         result.append("#");
57         for (int64_t value : item.second) {
58             sum += value;
59             result.append(std::to_string(value));
60             result.append("#");
61         }
62         result.append("average#");
63         result.append(std::to_string(static_cast<uint64_t>(sum) / item.second.size()));
64         result.append("\n");
65     }
66 
67     return result;
68 }
69 
70 JsApiPerf JsApiPerf::instance_;
71 
GetInstance()72 JsApiPerf& JsApiPerf::GetInstance()
73 {
74     return instance_;
75 }
76 
77 } // namespace OHOS::Ace::Framework
78