import concurrent.futures
import requests
import time
import json

cost_time = []
ALL_TIMES = 10000

def make_request(url, method='GET', data=None):
    try:
        start_time = int(time.time() * 1000)
        if method.upper() == 'POST':
            response = requests.post(url, json=data, headers={"content-type": "application/json;charset=UTF-8"})
        else:  # 默认使用GET方法
            response = requests.get(url, params=data)
        end_time = int(time.time() * 1000)
        elapsed_time = end_time - start_time
        cost_time.append(elapsed_time)
        return response.text, elapsed_time
    except requests.RequestException as e:
        return f"Request failed: {e}", None

def main():
    r_url = {'url': 'https://swagger.qa.huohua.cn/peppa-teach-timetable-server/timetableStudentServiceApi/queryListByIds',
             'method': 'POST', 'data': [225838679]}
    requests_list = [r_url] * ALL_TIMES

    m_start_time = int(time.time() * 1000)
    success_times = 0
    with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
        future_to_req = {executor.submit(make_request, req['url'], req['method'], req['data']): req for req in requests_list}
        for future in concurrent.futures.as_completed(future_to_req):
            req = future_to_req[future]
            try:
                data, elapsed_time = future.result()
                if data and json.loads(data).get('code') == 200:
                    success_times += 1
                # print(f"URL: {req['url']}\nMethod: {req['method']}\nData: {req['data']}\nResponse:\n{data}\nElapsed time: {elapsed_time:.2f} seconds\n")
                print("-----:本次耗时{}ms".format(elapsed_time))
            except Exception as e:
                print(f"Error fetching {req['url']}: {e}")
    m_end_time = int(time.time() * 1000)

    all_times = (m_end_time - m_start_time)/1000
    tps = ALL_TIMES / all_times
    print("共计访问接口：{}次，成功访问接口：{}次，持续时长：{}秒，tps: {}"
          .format(len(cost_time), success_times, all_times, tps))
    print("成功访问接口：{}次".format(success_times))
    print("单次最大耗时：{}ms".format(max(cost_time)))
    print("单次最小耗时：{}ms".format(min(cost_time)))
    print("单次平均耗时：{}ms".format(sum(cost_time) / len(cost_time)))


if __name__ == "__main__":
    main()