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#ifndef ECMASCRIPT_MEM_CLOCK_SCOPE_H
17#define ECMASCRIPT_MEM_CLOCK_SCOPE_H
18
19#include <ctime>
20#include <chrono>
21
22namespace panda::ecmascript {
23class ClockScope {
24using Clock = std::chrono::high_resolution_clock;
25using Duration = std::chrono::duration<uint64_t, std::nano>;
26
27public:
28    ClockScope()
29    {
30        start_ = Clock::now();
31    }
32
33    void Reset()
34    {
35        start_ = Clock::now();
36    }
37
38    Duration GetPauseTime() const
39    {
40        return Clock::now() - start_;
41    }
42
43    float TotalSpentTime() const
44    {
45        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - start_);
46        return (float) duration.count() / MILLION_TIME;
47    }
48
49    int TotalSpentTimeInMicroseconds() const
50    {
51        return std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - start_).count();
52    }
53
54    double GetCurTime() const
55    {
56        auto curTime_ = Duration(start_.time_since_epoch());
57        return (double) curTime_.count() / MILLION_TIME;
58    }
59
60private:
61    NO_COPY_SEMANTIC(ClockScope);
62    NO_MOVE_SEMANTIC(ClockScope);
63
64    Clock::time_point start_;
65    static constexpr uint32_t MILLION_TIME = 1000;
66};
67}  // namespace panda::ecmascript
68#endif  // ECMASCRIPT_MEM_CLOCK_SCOPE_H
69