Python实现的HTTP并发测试完整示例

(编辑:jimmy 日期: 2024/10/3 浏览:2)

可修改变量thread_count指定最大的并发数量,即线程的数量。

完成之后,打印输出失败的次数,以及开始时间和结束时间,单位是毫秒。

主要是学习一下Python,仅供参考。

#!/usr/bin/python3

import sys, time, json, _thread
import http.client, urllib.parse

thread_count = 100  #并发数量
now_count = 0
error_count = 0
begin_time = ''

lock_obj = _thread.allocate()

def test_http_engine():
  global now_count
  global error_count
  global thread_count
  global begin_time
  conn = None
  if now_count == 0:
    begin_time = int(round(time.time() * 1000))
  try:
    conn = http.client.HTTPConnection("192.168.1.1", 80)
    conn.request('GET', '/')

    response = conn.getresponse()
    data = response.read()
    print (data)

    if json.dumps(response.status) != '200':
      error_count += 1;
      print ('error count: ' + str(error_count))

    sys.stdout.flush()
    now_count += 1
    if now_count == thread_count:
      print ('### error count: ' + str(error_count) + ' ###')
      print ('### begin time : ' + str(begin_time))
      print ('### end time  : ' + str(int(round(time.time() * 1000))))

  except Exception as e:
    print (e)
  finally:
    if conn:
      conn.close()

def test_thread_func():
  global now_count
  global lock_obj
  cnt = 0

  lock_obj.acquire()
  print ('')
  print ('=== Request: ' + str(now_count) + ' ===')

  cnt += 1
  test_http_engine()
  sys.stdout.flush()
  lock_obj.release()


def test_main():
  global thread_count
  for i in range(thread_count):
    _thread.start_new_thread(test_thread_func, ())

if __name__=='__main__':
  test_main()
  while True:
    time.sleep(5)
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。