1 /**
2 * Copyright (c) 2021-2022 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 panda::time {
23
24 constexpr size_t TIME_BUFF_LENGTH = 100;
25
Timer(uint64_t * duration,bool need_restart)26 Timer::Timer(uint64_t *duration, bool need_restart) : duration_(duration), start_time_(GetCurrentTimeInNanos())
27 {
28 if (need_restart) {
29 *duration = 0;
30 }
31 }
32
~Timer()33 Timer::~Timer()
34 {
35 *duration_ += GetCurrentTimeInNanos() - start_time_;
36 }
37
GetCurrentTimeString()38 PandaString GetCurrentTimeString()
39 {
40 PandaOStringStream result_stream;
41 auto time_now = GetCurrentTimeInMillis(true);
42 auto millisecond = static_cast<time_t>(time_now % MILLISECONDS_IN_SECOND);
43 auto seconds = static_cast<time_t>(time_now / MILLISECONDS_IN_SECOND);
44
45 constexpr int DATE_BUFFER_SIZE = 16;
46 PandaString date_buffer;
47 date_buffer.resize(DATE_BUFFER_SIZE);
48 std::tm *now = std::localtime(&seconds);
49 ASSERT(now != nullptr);
50 if (std::strftime(date_buffer.data(), DATE_BUFFER_SIZE, "%b %d %T", now) == 0U) {
51 return "";
52 }
53 // Because strftime returns a string in C format
54 date_buffer[DATE_BUFFER_SIZE - 1] = '.';
55 result_stream << date_buffer << std::setfill('0') << std::setw(PRECISION_FOR_TIME) << millisecond;
56 return result_stream.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 panda::time
73