# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from npu_bridge.npu_init import *
import time
import numpy as np

G_TIMERS = {}
G_TM_BEGINS = {}

def TM_CLEAR():
    G_TIMERS = {}

def TM_DECLEAR(name):
    if name not in G_TIMERS:
        G_TIMERS[name] = []

def TM_BEGIN(name):
    G_TM_BEGINS[name] = time.time()

def TM_END(name):
    t = time.time()
    TM_DECLEAR(name)
    G_TIMERS[name].append(t - G_TM_BEGINS.pop(name, t))

def TM_DISPLAY(remove_first_one=True):
    for key, values in G_TIMERS.items():
        startPos = 0
        if remove_first_one:
            startPos = 1
            if len(values) <= 1:
                continue
        print("{}:{} times, cost time avg:{}".format(key, len(values), np.average(values[startPos:])))

def TM_PICK(name):
    if name not in G_TIMERS or len(G_TIMERS[name])==0:
        return None
    else:
        return G_TIMERS[name][-1]


