# coding=utf-8
# Copyright 2022 Gen Luo. 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.

import time

import torch


@torch.no_grad()
def throughput(model, img_size=224, bs=1, through_put_times=1000, device="cuda"):
    with torch.no_grad():
        single_input = torch.randn(bs, 3, img_size, img_size).to(device)
        batch_size = single_input.shape[0]
        model.eval()
        for i in range(50):
            model(single_input)
        torch.cuda.synchronize()
        # print(f"throughput averaged with {through_put_times} times")
        tic1 = time.time()
        for i in range(through_put_times):
            model(single_input)
        torch.cuda.synchronize()
        tic2 = time.time()
        through_put = through_put_times * batch_size / (tic2 - tic1)
        # print(f"batch_size {batch_size} throughput {through_put_times * batch_size / (tic2 - tic1)}")
        return through_put
