Python實現的HTTP併發測試程序

可修改變量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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章