1 /**
2 * Copyright (c) 2021-2024 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 "runtime/include/time_utils.h"
17
18 #include <iomanip>
19
20 #include "libpandabase/utils/time.h"
21
22 namespace ark::time {
23
24 constexpr size_t TIME_BUFF_LENGTH = 100;
25
Timer(uint64_t * duration,bool needRestart)26 Timer::Timer(uint64_t *duration, bool needRestart) : duration_(duration), startTime_(GetCurrentTimeInNanos())
27 {
28 if (needRestart) {
29 *duration = 0;
30 }
31 }
32
~Timer()33 Timer::~Timer()
34 {
35 *duration_ += GetCurrentTimeInNanos() - startTime_;
36 }
37
GetCurrentTimeString()38 PandaString GetCurrentTimeString()
39 {
40 PandaOStringStream resultStream;
41 auto timeNow = GetCurrentTimeInMillis(true);
42 auto millisecond = static_cast<time_t>(timeNow % MILLISECONDS_IN_SECOND);
43 auto seconds = static_cast<time_t>(timeNow / MILLISECONDS_IN_SECOND);
44
45 constexpr int DATE_BUFFER_SIZE = 16;
46 PandaString dateBuffer;
47 dateBuffer.resize(DATE_BUFFER_SIZE);
48 std::tm *now = std::localtime(&seconds);
49 ASSERT(now != nullptr);
50 if (std::strftime(dateBuffer.data(), DATE_BUFFER_SIZE, "%b %d %T", now) == 0U) {
51 return "";
52 }
53 // Because strftime returns a string in C format
54 dateBuffer[DATE_BUFFER_SIZE - 1] = '.';
55 resultStream << dateBuffer << std::setfill('0') << std::setw(PRECISION_FOR_TIME) << millisecond;
56 return resultStream.str();
57 }
58
GetCurrentTimeString(const char * format)59 PandaString GetCurrentTimeString(const char *format)
60 {
61 std::string date {};
62 std::time_t time = std::time(nullptr);
63 std::tm *now = std::localtime(&time);
64 ASSERT(now != nullptr);
65 std::array<char, TIME_BUFF_LENGTH> buffer {};
66 if (std::strftime(buffer.data(), buffer.size(), format, now) != 0) {
67 date = std::string {buffer.data()};
68 }
69 return ConvertToString(!date.empty() ? date : "1970-01-01 00:00:00");
70 }
71
72 } // namespace ark::time
73